Skip to content

Project heterogeneous constraints - #4605

Closed
vlopezj wants to merge 63 commits into
masterfrom
future-hetcon
Closed

vlopezj wants to merge 63 commits into
masterfrom
future-hetcon

Conversation

@vlopezj

@vlopezj vlopezj commented Apr 17, 2020 •

Copy link
Copy Markdown
Collaborator

Superseded by #5234

Tracking progress and discussion on a branch for heterogeneous constraints.

This project aims to introduce the possibility of handling heterogeneous constraints in the conversion checker into Agda.

Background

Agda constraints are of the form Γ ⊢ t ≈ u : A.

These are represented internally as the Constraint datatype:

data Constraint
  = ValueCmp Comparison CompareAs {- A -} Term {- t -} Term {- u -}
  {- ... -}

The context Γ is carried around as envContext in the environment TCEnv
of the type-checking monad TCM.

In the current Agda, there are situations where one of Γ ⊢ t : A or Γ ⊢ u : A does not hold, which causes
issues.

Heterogeneous constraints introduce a twin context and type, so that constraints can be of the form
Γ₁‡Γ₂ ⊢ t ≈ u : A‡B, with Γ₁ ⊢ t : A or Γ₂ ⊢ u : B.

There are two immediate issues:

  • Adding the context so that it is available when the constraint is tackled.
  • Ensuring that when t : A and u : B are manipulated, it is done in the appropriate context.

Approach

The plan is to gradually introduce heterogeneous unification into Agda. The idea is to introduce
the heterogeneous contexts as additional information on top of the current heterogeneous contexts.
This additional information can be used when necessary in order to avoid bugs, while ignored
in those parts of the code that have not been upgraded. We will keep an eye on performance to make
sure that it stays comparable.

Progress

  • Step 0. Add a flag to enable heterogeneous unification:
    , Option []     ["heterogeneous-unification"] (NoArg heterogeneousUnificationFlag)
                    "use heterogeneous unification; hopefully slower but smaller chance of internal errors"
  This flag is enabled by default.
  • Step 1. Define wrappers to keep track of which side of the context a term lives in
type HetSide = LHS | RHS | Both | Whole | Compat
newtype Het (s :: HetSide) t = Het { unHet :: t }

By wrapping terms in a heterogeneous context in a Het @'LHS or Het @'RHS constructor, the Haskell typechecker will be able to point out those points in the code that need to be changed in order to handle heterogeneity.

  • Step 2. Add a data type to keep track of two sided types:
data TwinT'' b a  =
    SingleT (Het 'Both a)
  | TwinT { twinPid    :: [ProblemId]  -- ^ Unification problem which is sufficient
                                       --   for LHS and RHS to be equal
          , necessary  :: b            -- ^ Whether solving twinPid is necessary,
                                       --   not only sufficient.
          , twinLHS    :: Het 'LHS a            -- ^ Left hand side of the twin
          , twinRHS    :: Het 'RHS a            -- ^ Right hand side of the twin
          , twinCompat :: Het 'Compat a            -- ^ A term which can be used instead of the
                                      --   twin for backwards compatibility
                                      --   purposes.
          }
   deriving (Data, Show, Functor, Foldable, Traversable)
  • twinPid and necessary are a premature optimization used to determine when two sides of the context are equal.

  • twinLHS and twinRHS contain the left and right sides of the twin type, respectively.

  • twinCompat is used to downgrade the twin type to a single type in those parts of the code which cannot yet handle twins.

  • Step 3. Include the twin contexts with the constraints themselves, and add the following newtypes:

data Constraint
  = ValueCmp Comparison CompareAs {- A -} Term {- t -} Term {- u -}
  | ValueCmpHet Comparison TwinT  (Het 'LHS Term) {- t -} (Het 'RHS Term) {- u -}
  {- ... -}
  • Step 4. Replace the homogeneous context in TCEnv by a heterogeneous context. Those parts of the code that are not heterogeneous-aware will access use the twinCompat field.
newtype ContextHet = ContextHet { unContextHet :: Seq (Name, Dom TwinT) }

data TCEnv =
    TCEnv { envContext             :: ContextHet
          , envLetBindings         :: LetBindings
          {- ... -}
  • Step 5. If the flag --heterogeneous-constraints is enabled, introduce a variable with twin type in compareDom.
      {- ... -}
      heterogeneousUnificationEnabled >>= \case
        True ->
          addContext (name, dom0'{unDom =
                              TwinT{necessary  = True,
                                    twinPid    = [pid],
                                    twinLHS    = Het @'LHS a1,
                                    twinCompat = Het @'Compat a0',
                                    twinRHS    = Het @'RHS a2
                                   }}) cont
        False -> addContext (name, dom0') cont
      {- ... -}
  • Step 5½. Check the impact on performance.

The impact on performance seems small, with no evidence of increase in CPU time or memory.
Benchmarks.

  • Step 6. Introduce a machinery for compareElim based on heterogeneous constraints instead of antiunification.
    We aim to keep the antiunification result as the twinCompat part of the type.

    • This requires code to commute certain constructs (Π, type constructors, etc…)
      For instance, turning (ΠAB‡ΠA′B′) into Π(A‡A′)(B‡B′).
  • Step 7. Adapt compareTerm and compareAtom so that they can too handle heterogeneous constraints without downgrading them. We intend to perform downgrading to homogeneous constraints in the cubical side initially, to keep the scope restricted.

  • Step 8: Add code to check that a context is homogeneous before instantiating a metavariable.

    • We need to check that the types are equal, and the contexts are heterogeneously equal.
    • The code for checking should be added late enough so that the performance hit is incurred only if the metavariable is going to be instantiated.
  • Step 8½: Check if Issue3027 and others are now resolved, and if
    we can check the examples in the technical paper.

  • Step 9. …

Future work

  • Similarly transform the ElimCmp constructor in order to perform heterogeneous rigid-rigid unification (instead of antiunification).
  • Ensure that performance is adequate.
  • ...

Questions (Known unknowns)

  • Is the approach sensible?
  • What is the difference between a Context and a Telescope?
  • How will the approach interact with subtyping?
    For instance, currently compareDom uses the smaller of the two types.
    How does the heterogeneous equality translate to subtyping?
  • How do twin contexts interact with let bindings?
  • How will this interact with the checkpoint mechanism?
  • Would it be better to add the heterogeneous context to TCEnv instead of keeping it in the constraint itself?
  • Does syntactic equality need to be performed heterogeneously, or is it type-agnostic?

Journal

  • 2020-07-06: A first attempt tried to make TCEnv polymorphic in the type of envContext, so that the in the conversion algorithm one can have a twin context, those parts dealing with terms the usual one, and common parts would work in either. This quickly became unfeasible due to the dependency of big parts of the codebase on the MonadWarning machinery, which via MonadPretty, MonadReduce and MonadAddContext ultimately requires the usual context.
  • 2020-07-09: The approach of including the twin context in the constraint seems to work so far in terms of ease of integration. I have defined several instances for the new constraint type (ValueCmpHet).
  • 2020-07-13: I have modified compareDom so that the domain arguments can be given for in the correct order. Also, I collected some of the the instances of Semigroup for monads in a new Agda.Utils.Semigroup submodule.
  • 2020-07-14: Started systematic benchmark of commits in this branch against a subset of the Agda benchmarks, to assess how the changes impact performance.
  • 2020-07-22: Added some utility code to be able to write code that handles both the homogeneous and the heterogeneous versions of a constraint.
  • 2020-07-23: Carrying around the context and manually localizing it to the appropriate side is painful.
    See second attempt. I will test an approach where a (potentially) heterogeneous context is carried around in the environment. This will hopefully allow most of the code to remain unchanged, with switching of contexts happening only where needed.
    The main issue is how to handle context manipulations, but hopefully these can be fixed on a case-by-case basis.
  • 2020-07-31: We have switched to carrying the heterogeneous context in TCEnv. So far it seems to work without issues, and requires few modifications.

References

@vlopezj vlopezj added the status: do-not-merge So please don't merge label Apr 17, 2020
@vlopezj
vlopezj force-pushed the future-hetcon branch 4 times, most recently from 0e3e1e7 to 31909a6 Compare July 3, 2020 09:13
@vlopezj
vlopezj force-pushed the future-hetcon branch 5 times, most recently from 9d68447 to b673f5d Compare July 7, 2020 13:22
@vlopezj
vlopezj marked this pull request as draft July 7, 2020 13:43
@vlopezj

vlopezj commented Jul 7, 2020

Copy link
Copy Markdown
Collaborator Author

With the aim of solving the issues in https://github.com/agda/agda/projects/3, I am currently implementing into Agda the heterogeneous unification approach described in @nad's and my upcoming paper.

@UlfNorell @andreasabel @jespercockx I see that you have authored large parts of Agda.TypeChecking.Conversion, which I expect to modify and extend in the process.
I would be glad if you can take a look at my current plans and say if they look feasible, what you would do differently, and any other things I should consider.

@vlopezj
vlopezj force-pushed the future-hetcon branch 3 times, most recently from 7c07896 to 0cfb762 Compare July 17, 2020 10:31
@vlopezj
vlopezj force-pushed the future-hetcon branch 4 times, most recently from 1b0de91 to 1411c7d Compare July 22, 2020 16:07
@vlopezj

vlopezj commented Dec 18, 2020

Copy link
Copy Markdown
Collaborator Author

I have implemented the changes in compareTerm, compareAtom, and the metavariable assign routine. This solves (the longstanding) issue #3027.

The performance becomes 5-6% slower than Agda when typechecking the standard library
(c.f. Any benchmark, 126 seconds for future-hetcon vs 119 seconds for master).

https://lopezjuan.com/res/file/2020/evaluation-future-hetcon-2020-12-18.html

I am currently working on implementing heterogeneous unification of elimination spines (step 6). This may allow us to get rid of antiunification.

A working Agda with heterogeneous unification (Heterogeneous Agda) can be found in the future-hetcon branch. All tests in the test suite run correctly.

If you have an example which either does not work properly, or becomes much slower, tell me and I can add it both to the benchmark suite and to the test suite for this branch.
Comments about code style are also welcome.

@vlopezj

vlopezj commented Jan 13, 2021

Copy link
Copy Markdown
Collaborator Author

I have started an implementation of heterogeneous unification for spines.

Current commit: 9ae5de2...vlopezj:a8f3a97
Whole branch: future-hetcon...vlopezj:future-hetcon

Currently the changes result in many blocked constraints. For efficiency, twins are tagged with problem ids such that when that problem is solved, both sides of the twin are heterogeneously equal. However, it often happens that the associated problem is sufficient but not necessary.

A mechanism is needed so that both sides of a twin can be re-checked for equality so that the constraint does not block unnecessarily. Doing this effectively may require some mechanism for prioritizing constraints, so that new constraints are only introduced as a last resort. One option is to integrate this with the blocker mechanism, adding a special blocker which just unblocks at a later "epoch".

# Conflicts:
#	src/full/Agda/TypeChecking/Conversion.hs
#	src/full/Agda/TypeChecking/Conversion/Pure.hs
#	test/Fail/Issue3882.err
# Conflicts:
#	stack-8.0.2.yaml
# Conflicts:
#	src/full/Agda/TypeChecking/Conversion.hs
#	src/full/Agda/TypeChecking/Conversion.hs-boot
#	src/full/Agda/TypeChecking/Heterogeneous.hs
@vlopezj

vlopezj commented Feb 10, 2021

Copy link
Copy Markdown
Collaborator Author

I have implemented heterogeneous unification for spines.
This had by far the most impact on the flexibility and performance of the Conversion checker.

Work done so far: https://github.com/agda/agda/compare/future-hetcon-elim
Performance analysis: https://lopezjuan.com/res/file/2021/evaluation-future-hetcon.html

Main gains:

Main issues:

Next steps:

  • Fix compilation of the Cubical library (even if it's just by disabling heterogeneous unification when --cubical is enabled).

@vlopezj vlopezj mentioned this pull request Feb 25, 2021
1 of 23 tasks
@vlopezj

vlopezj commented Feb 25, 2021

Copy link
Copy Markdown
Collaborator Author

Superseded by #5234

@vlopezj vlopezj closed this Feb 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: do-not-merge So please don't merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants