메뉴
HN
Hacker News 54일 전

AI, 다각형 교차 영역 형식 검증 최초 성공

IMP
9/10
핵심 요약

최신 AI 모델을 활용해 폴리곤 교차 알고리즘을 수학적으로 엄격하게 증명(형식 검증)하는 데 처음으로 성공한 사례입니다. 과거에는 인간이 여러 단계로 증명 전략을 제시해야 했으나, 최신 모델은 한 번의 프롬프트로 완벽한 코드와 증명을 생성해 냈습니다. 정확성은 AI가 아닌 Lean 4 증명 보조기와 87줄의 짧은 명세 코드를 통해 100% 보장되며, 웹 데모를 통해 직접 테스트해 볼 수 있습니다.

번역된 본문

형식 검증된 다중 다각형 교차 알고리즘

제가 아는 한, 이것은 다각형 교차 알고리즘의 최초로 형식 검증된 구현입니다. (관련 연구와 비교해 보세요.) 최신 모델 출시와 함께 이 프로젝트에서 AI 에이전트를 다루는 경험은 크게 달라졌습니다. 이전 모델들은 여러 단계에 걸쳐 증명 전략을 제공받아야 했던 반면, 최신 모델은 단 한 번의 프롬프트(One-shot)로 형식 증명이 포함된 알고리즘 구현을 제공할 수 있습니다. (AI 에이전트의 능력)

알고리즘의 올바름에 대한 신뢰는 전적으로 Lean 검사기(Lean checker)와 소규모 명세(specification)에 대한 인간의 검토에서 비롯되며, LLM에서 나오는 것이 아닙니다. (AI 에이전트 사용법 참고)

직접 사용해 보기 검증된 핵심 코드를 바탕으로 구축된 웹 데모를 통해 다중 다각형을 그리고 교차시켜 볼 수 있습니다.

배경 다중 다각형 교차는 많은 벡터 그래픽 편집기의 표준 기능입니다. 다중 다각형은 꼭짓점 목록으로 정의되는 다각형 컴포넌트와 다각형 구멍들의 목록으로 정의됩니다. 이는 2차원 영역, 즉 내부 점들의 집합을 설명합니다. 이 집합은 평면의 각 점에서 쏜 반직선(Ray)과 다각형의 교차 횟수의 패리티(홀짝)를 세어 형식적으로 정의할 수 있습니다. 두 개의 다중 다각형이 주어지면, 입력 다중 다각형 두 개의 내부 집합의 교집합을 내부 집합으로 갖는 새로운 다중 다각형을 구성합니다.

입력 다각형의 구성은 무한히 많기 때문에, 형식 검증 없이는 고전적인 테스트만으로 모든 구성에 대한 속성을 완벽하게 검증할 수 없습니다. 또한 각 다각형에 대해 내부 점의 집합은 무한하므로, 형식 검증이 없다면 내부 집합과 그 교집합은 코드로 표현할 수 없는 단순한 해석에 불과합니다. 본 개발에서는 교차 명세가 형식적으로 기술되었으며, Lean 4 증명 보조기를 통해 완전히 검증되었습니다. 따라서 입력 다각형의 어떠한 구성에 대해서도 이러한 무한한 내부 점 집합이 실제로 교차 등식을 만족한다고 보장할 수 있습니다.

이러한 계산 기하학 알고리즘의 구현은 고전적인 테스트로 검증하기가 악명 높게 어려운데, 그 이유는 입력의 드문 특수 구성이 알고리즘 복잡성의 대부분을 차지할 수 있기 때문입니다. 예를 들어, 십자가(아래 그림의 파란색 다각형)와 구멍이 있는 정사각형(그림의 노란색 다각형)을 교차시키는 경우를 생각해 보세요. 교차 영역을 설명하는 다중 다각형을 생성하려면 알고리즘이 닫힌 경계 컴포넌트를 선택하고 꼭짓점의 순서를 정해야 합니다. 어떤 녹색 선분들이 함께 묶일지에 대한 선택은 이 경우 유일하지 않습니다(예를 들어 4개의 정사각형이 될 수도 있고, 정사각형 구멍이 있는 십자가가 될 수도 있음). 하지만 노란색 구멍이 아주 약간만 작아지거나 커져도 이 선택은 유일해집니다. 모든 경우에 선분들을 닫힌 경계 컴포넌트로 분할하고 순서를 정하는 것이 가능하다는 것은 (오일러 회로와 관련된) 자명하지 않은 사실입니다.

이 저장소에서 형식 검증의 길이는 대부분 알고리즘 자체에서 비롯된 것이 아니라, 겉보기에 명백해 보이는 많은 기하학적 사실들이 짧고 엄격한 증명을 가지고 있지 않기 때문입니다. 앞서 설명한 '내부'의 정의가 반직선의 방향과 무관하다는 증명만으로도 수천 줄의 Lean 코드가 필요했습니다.

AI 에이전트의 활용 이 저장소의 설정은 다각형 교차 알고리즘 구현의 올바름을 검증하는 데 필요한 인간의 검토를 최소화하는 것을 목표로 합니다. 인간 검토자는 단지 DataStructures.lean, Defs.lean, MultipolygonIntersectionAlgorithmWithPreconditionCheck.lean이라는 3개의 파일을 읽고 Lean 검사기를 실행하기만 하면 됩니다. 이는 이해하기 쉬운 87줄의 Lean 명세로, 주로 다각형에 대한 기본적인 기하학적 정의를 설정하는 것입니다.

알고리즘을 구현하는 최적화되지 않은 코드는 이미 그 두 배 이상이며 이해하기도 더 복잡합니다. 최적화를 추가하면 코드는 훨씬 더 길어질 것입니다. 반면, 올바름을 검토하기 위해 인간이 읽어야 하는 명세는 동일한 크기를 유지할 것입니다. 올바름을 검토하기 위해 다른 파일을 읽을 필요는 없습니다.

원문 보기
원문 보기 (영어)
Formally verified multipolygon intersection To my knowledge, this is the first formally verified implementation of an intersection algorithm for polygons. (Also compare with Related work ) The experience of working with AI agents on this project changed a lot with recent model releases. Latest models are able to provide algorithm implementation with formal proof in one shot, whereas previous models required me to provide proof strategies in multiple steps. ( Capabilities of AI agents ) Trust in the correctness comes entirely from the Lean checker and human review of a small specification, not from the LLM. (See Use of AI agents ) Try it out Try out the web demo built around the verified core, where you can draw and intersect multipolygons. Background Multipolygon intersection is a standard feature of many vector graphic editors. A multipolygon is defined by a list of polygon components and polygonal holes, each defined by a list of vertices. It describes a two-dimensional area: the set of interior points. This set can be formally defined by counting the parity of the number of intersections of the polygon with rays cast from each point on the plane. Given two multipolygons, we construct a new multipolygon, whose interior set is the intersection of the two interior sets of the input multipolygons. There are infinitely many configurations of input polygons, so without formal verification no property can be exhaustively verified for every configuration by classical testing. Furthermore, for each polygon the set of interior points is infinite, so without formal verification interior sets and their intersection are just an interpretation that cannot be represented in the code. In this development the intersection specification is formally described and fully verified with the Lean 4 proof assistant. So we can guarantee that these infinite sets of interior points actually satisfy the intersection equality, for any configuration of input polygons. Implementations of computational geometry algorithms like this are notoriously hard to verify by classical testing, because of rare special configurations of inputs that may make up much of the complexity of the algorithm. Consider for example the following example where we intersect a cross (blue polygon in picture below) with a square with a hole (yellow polygons in the picture). To produce a multipolygon that describes the intersection, the algorithm must choose closed boundary components and order the vertices. This choice of which green segments belong together is not unique in this case (for example it could be 4 squares or a cross with a square hole), but it would be unique if the yellow hole were a tiny bit smaller or larger. It is a non-trivial fact (related to Eulerian cycles) that it is possible to partition and order the segments into closed boundary components in all cases. The length of the formal verification in this repository mostly does not come from the algorithm, but from the fact that many seemingly obvious geometrical facts have no short rigorous proof. Only the proof that definition of "inside" described above is independent from the direction of the ray took thousands of lines of lean. Use of AI agents The setup of this repository aims to minimize human review needed to verify correctness of the implementation of the polygon intersection algorithm. A human reviewer just needs to read the 3 files DataStructures.lean , Defs.lean and MultipolygonIntersectionAlgorithmWithPreconditionCheck.lean and run the Lean checker. These are 87 lines of simple-to-understand Lean specification, mostly setting up basic geometrical definitions for polygons. The unoptimized code implementing the algorithm is already more than twice that and more complicated to understand. The code will grow a lot once we add optimizations. The specification that humans have to read to review correctness, on the other hand, will stay the same size. It is not necessary to read other files to review correctness. I also read and directed the content of other files that don't end in ...Proofs.lean and ...Impl.lean to steer the strategy (pre Opus 4.8, see Capabilities of AI agents ). The main theorems in these other files served as checkpoints, so I could use the Lean checker to determine when the agent actually succeeded at a task. The implementation and formal proof of its correctness in the ...Proofs.lean and ...Impl.lean files was autonomously written by AI agents and never reviewed by me or any other human, but thanks to the Lean checker, neither I nor any human reviewer needs to trust any LLM in this process. The way this separation is structured is described in CLAUDE.md and may not be Lean-idiomatic. A drawback I observed from forcing AI agents to formally verify their implementation is that this tends to produce code that is slower or disregards other practical considerations that are not captured in the specification. This probably stems from the difficulty of the formal verification pushing for simpler code and from the lack of formally verified practical software in the training data. Capabilities of AI agents The experience of working with AI agents on this project changed a lot with recent model releases: My first attempt at this project was at the beginning of the year, using Claude Opus 4.5 and 4.6. In my experience Opus 4.5 was the first model that could handle non-trivial lean proofs. But it was at the level, that only when I was able to sketch out a perfectly rigorous proof, it would translate it to Lean. For example I needed to split the proof that the definition of the interior set using the ray intersection is independent of the ray directions, into many small steps. I was then stuck at this project until Claude Opus 4.7 came out. Claude Opus 4.7 enabled to take larger steps. It could prove that for every two polygons, there exists an intersection, but I still needed to provide the idea to use Eulerian circuits and in separate steps give it hints how to handle some tricky special cases. And from this theorem it was then able to autonomously extract a formally verified algorithm. The day after the release, I tried Claude Opus 4.8 in ultracode mode. I started two sessions in parallel: One to reprove the main polygon intersection theorem, which is almost all of the previously done work, from scratch with no hints (in an isolated container to avoid peeking at the solution). See github.com/schildep/challenge-verified-polygon-intersection-Opus-4.8 . Another to extend the algorithm to handle special cases regarding overlapping segments, where previous Opus 4.7 sessions failed. To my surprise, both of these sessions succeeded after a few hours of autonomous work. It was able to formulate and execute large proof strategies. One thing that I observed from looking at the intermediate output of Opus 4.8, is that it actually seems to much more accurately handle the risk of wrong intermediate theorems: To prove a large theorem you have to take risk of loosing time trying to prove helper theorems that a priori might be incorrect. Where previous models got stuck at trying to prove an incorrect intermediate theorem, Opus 4.8 became suspicious, and autonomously pivoted to a different strategy or at another occasion it decided to run parallel subagents to try multiple strategies. Building and checking Requires elan . The Lean version is pinned in lean-toolchain (currently leanprover/lean4:v4.15.0 ) to simplify the WebAssembly build. Check all proofs: lake build Inspect the axioms the theorems of interest depend on (e.g. here correctness theorem of the algorithm). This is important since agents could have introduced unwanted axioms into the proofs. We only depend on trusted axioms [propext, Classical.choice, Quot.sound] . printf 'import Polygons.MultipolygonIntersectionAlgorithmWithPreconditionCheck\n#print axioms multipolygonIntersectionAlgorithmWithPreconditionCheck_interior_eq\n#print axioms multipolygonIntersectionAlgorithmWi