메뉴
HN
Hacker News 19시간 전

1000줄 AI 코드 대신 93줄 명세 신뢰하기: 형식 검증된 3D CSG

IMP
8/10
핵심 요약

이 프로젝트는 3D 형상 연산(교집합) 알고리즘을 Lean 4로 구현하고 형식 검증(Formal verification)을 거친 사례입니다. 개발자는 복잡한 1,000줄 이상의 AI 생성 코드를 직접 검토할 필요 없이, 사람이 작성한 93줄의 핵심 명세와 Lean 컴파일러의 검증 결과만 신뢰하면 됩니다. 이를 통해 AI가 작성한 방대한 양의 코드와 증명 과정을 블랙박스로 처리하면서도 소프트웨어의 수학적 정확성을 완벽하게 보장받을 수 있음을 보여줍니다.

번역된 본문

형식 검증된 3D 메시 교차 연산 - 1,000줄 이상의 AI 작성 코드가 아닌 93줄의 명세를 신뢰하라.

제가 아는 한, 이 프로젝트는 3D CSG(구조적 입체 기하학, Constructive Solid Geometry) 연산에 대한 최초의 형식 검증된 구현체입니다. Lean 4로 구현된 메시 교차 연산은 결과 메시의 표면을 정확하게 정의하고 삼각화에 대한 실용적인 잘 형성됨(Well-formedness) 조건을 보장하는 간결한 명세에 대해 검증되었습니다. (관련 연구 참조.) 이 프로젝트는 AI가 생성한 코드를 무비판적으로 신뢰해야 하는 상황을 피하기 위한 실험이기도 합니다. 인간 검토자는 1,000줄이 넘는 복잡한 AI 작성 구현체를 검토할 필요 없이, 단 93줄의 공식 명세를 읽고 아래 설명된 대로 Lean 검사기를 실행하는 것만으로 커널의 정확성을 인증할 수 있습니다.

정확성을 증명하기 위해 AI는 자율적으로 60,000줄 이상의 Lean 증명을 작성했으며, 이마저도 인간이 일일이 검사할 필요가 전혀 없습니다. 컴파일 시점에 Lean 검사기가 명세에 대한 부합 여부를 보장하므로 LLM(대형 언어 모델)에 대한 어떠한 신뢰도 필요로 하지 않습니다. 이를 통해 우리는 구현체와 증명 과정을 완전한 블랙박스로 취급할 수 있습니다. 저는 AI 에이전트가 아래에 설명된 여러 마일스톤을 거치도록 안내하여 여기에 제시된 결과를 도출할 수 있었습니다.

웹 데모 검증된 커널을 기반으로 구축된 웹 데모를 사용해 볼 수 있습니다. 데모에서 예제 메시를 교차시키거나 STL 파일에서 메시를 가져와 교차시킬 수 있습니다. 컴파일된 Lean 코드는 브라우저에서 로컬로 실행되며, 어떠한 데이터도 서버로 전송되지 않습니다. 커널 자체는 형식적으로 검증되었지만, UI와 이를 연결하는 글루(glue) 코드는 검증되지 않았다는 점에 유의하십시오. 당사의 구현체는 최신 기술 수준의 메시 교차 구현체보다 훨씬 느립니다. 7만 개의 삼각형으로 이루어진 스탠퍼드 토끼(Stanford bunny) 두 개의 정확한 교차 연산을 계산하는 데 24초가 소요됩니다. 이 프로젝트에서는 성능보다 정확성에 대한 인간의 검토 노력을 최소화하는 것을 우선시했습니다. 이러한 성능 격차는 형식 검증된 소프트웨어의 근본적인 한계가 아니며, 원칙적으로 기존 소프트웨어만큼 빠를 수 있다는 점을 참고하시기 바랍니다. 자세한 내용은 본문을 참조하세요. 출력되는 메시는 아래에 설명된 속성들을 만족하는 것이 보장되지만, 아직 공식화하지 않은 다른 기준과 관련해서는 메시 생성 결과가 최적이 아닐 수 있습니다. 예를 들어, 필요 이상으로 세분화된(finer) 메시가 생성될 수 있습니다.

배경 및 공식화 삼각형 메시(Triangle mesh)는 일반적으로 아래에서 논의할 잘 형성됨(Well-formedness) 조건 외에도 스스로 교차하지 않고 닫힌 표면을 형성할 것으로 기대되는 삼각형들의 집합입니다. 인간은 직관적으로 삼각형 메시를 3D 공간의 부피, 즉 표면이 아닌 메시 '내부'에 있는 모든 점들의 집합인 '입체(Solid)'와 연관 짓습니다. ('내부'는 부호가 있는 광선 교차 수학적 계수로 설명할 수 있습니다.) 실제 메시 데이터 구조를 다루는 구현체가 복잡하고 수많은 기하학적 특수한 경우를 전용 코드로 처리해야 함에도 불구하고, 이러한 입체의 개념 덕분에 우리는 메시 교차 알고리즘과 같은 알고리즘의 출력이 어떤 형태여야 하는지 이해할 수 있습니다.

메시 교차 알고리즘에서 우리는 잘 형성된 입력 메시의 입체 집합의 교집합이 출력 메시의 입체가 되어야 하며, 그 출력 역시 다시 잘 형성된 메시여야 한다고 기대합니다. (또한 입력이 잘 형성되지 않은 경우 이를 감지하고 올바르게 보고할 것으로 기대합니다.)

solid (meshIntersect M₁ M₂) = solid M₁ ∩ solid M₂

이는 결과 메시의 표면을 교차된 입체들의 경계선으로 정확하게 규정합니다. 삼각형 메시를 다루는 알고리즘은 우리가 의도하는 입체를 나타내는 메시를 효율적으로 계산할 수 있지만, 기존의 프로그래밍 언어에서는 '입체'가 무한 집합이기 때문에 이를 명시적으로 표현하거나 관련 명제를 만들 수 없습니다. Lean에서는 이것이 가능하여, 예를 들어 이러한 무한 집합을 교차시키거나 두 무한 집합이 동일하다는 것을 증명할 수 있습니다. 더 나아가, Lean을 사용하면 특정 함수가 가능한 모든 입력 메시에 대해 조건을 만족한다는 것을 증명할 수 있는 반면, 기존 프로그래밍 언어는 특정 입력에 대해서만 함수가 조건을 만족하는지 테스트하는 것만 허용합니다. 우리는 메시의 상태를 포착하기 위해 메시의 잘 형성됨(Well-formedness)을 다음과 같이 정의합니다.

원문 보기
원문 보기 (영어)
Formally verified 3D mesh intersection - trust 93 lines of spec, not 1000+ lines of AI-written code To my knowledge, this is the first formally verified implementation of a 3D constructive solid geometry (CSG) operation: mesh intersection, implemented in Lean 4 and verified against a concise specification that pins down the surface of the resulting mesh exactly and guarantees practical well-formedness conditions on the triangulation. (See also related work .) This project is also an experiment in avoiding having to trust AI-generated code. A human reviewer only needs to read 93 lines of formal specification and run the Lean checker as described below to certify the correctness of the kernel, skipping the intricate 1000+ lines of AI-written implementation. To prove correctness, AI autonomously wrote over 60,000 lines of Lean proofs, which also never have to be inspected by a human. The Lean checker guarantees conformance to the specification at compile time, with zero trust placed in any LLM. This allows us to treat the implementation and proofs as a black box. I guided the agent through the milestones described below to arrive at the result presented here. Web demo Try out the web demo built around the verified kernel, where you can intersect example meshes or import and intersect meshes from STL files. The compiled Lean code runs locally in your browser; no data is ever sent to a server. Note that while the kernel is formally verified, the UI and glue code are not. Our implementation is far slower than state-of-the-art mesh intersection implementations: it takes 24 seconds to compute the exact intersection of two 70k-triangle Stanford bunnies. In this project we prioritize minimizing the effort of human review of correctness over performance. Note that this performance gap is not a fundamental limitation of formally verified software, which can in principle be as fast as conventional software. See details . The output meshes are guaranteed to satisfy the properties described below, but the meshing may be suboptimal with respect to other criteria that we did not yet formalize; for example, it may produce a mesh that is finer than necessary. Background and formalization A triangle mesh is a set of triangles, usually expected to form a closed surface that does not penetrate itself, among other well-formedness conditions we will discuss below. Humans intuitively associate triangle meshes with a "solid", i.e. a volume in 3D space: the set of all points not on the surface but "inside" the mesh. ("Inside" can be described mathematically by signed ray intersection counting.) This concept of solids allows us to understand what the output of algorithms such as a mesh intersection algorithm should look like, even when the implementation that works on the actual mesh data structure is intricate and has to treat many geometrical special cases with dedicated code. From a mesh intersection algorithm, we expect that the set intersection of the solids of well-formed input meshes is the solid of the output mesh and that the output is a well-formed mesh again. (We also expect that the algorithm detects and reports correctly if the inputs are not well-formed.) solid (meshIntersect M₁ M₂) = solid M₁ ∩ solid M₂ This pins down the surface of the resulting mesh exactly as the boundary of the intersected solids. Algorithms working on triangle meshes can efficiently compute meshes representing solids we have in mind, but conventional programming languages cannot express "solids" explicitly or make statements about them, since these are infinite sets. In Lean this is possible and we can for example intersect such infinite sets or prove that two infinite sets are equal. Moreover, Lean allows us to prove that a function satisfies a condition for all possible input meshes, whereas conventional programming languages only allow us to test that the function satisfies a condition for specific inputs. We define well-formedness of meshes to capture the conditions commonly expected by real-world mesh processing tools - watertight surface, bounding a solid with multiplicity one with coherent outward orientation, no degenerate triangles, no self-intersections - with one relaxation: the surface may touch itself, not at the interiors of faces but along edges and vertices. So strict 2-manifoldness is not required. See why an intersection algorithm that always produces manifold meshes is not possible . Minimal human review without trusting AI In order to certify correctness of the kernel, which checks the well-formedness preconditions of the inputs and computes the mesh intersection, a reviewer only needs to read 93 lines of formal specification and run the Lean checker as described below . The reviewer can skip the intricate 1000+ lines of AI-written implementation of the algorithm. The Lean checker guarantees conformance to the specification at compile time, with zero trust assumptions on any LLM. It suffices to read the files CSG/DataStructures.lean , CSG/Def.lean , CSG/MeshIntersectWithPreconditionCheck.lean and CSG/WellFormedCheckMsg.lean and run the Lean checker as described below. These are just 93 lines of code, excluding comments. Other files do not need to be read, since the theorem statements that specify meshIntersectWithPreconditionCheck (in the file with the same name) only rest on definitions stated in these 4 files. A reviewer can skip the implementation of meshIntersectWithPreconditionCheck that reaches over 1000 lines of code in 4 files in CSG/Impl/ , since it is guaranteed by the deterministic Lean checker to conform to the human-reviewed specification. This works thanks to 60,000 lines of AI-written formal proofs in CSG/Proof/ , which also never have to be inspected by a human. This compression and simplification from the implementation to the specification is possible because many things the implementation has to deal with can be completely decoupled from the specification: The implementation has to handle special geometrical cases , which make up much of the complexity of the algorithm, whereas the formal specification is short because the math can be formulated generally. The Lean checker guarantees that all special cases are handled in accordance with the specification without the specification enumerating the special cases. The implementation uses accelerating data structures in order to avoid quadratic runtime complexity and other optimizations. While we did not formalize runtime complexity, the Lean checker guarantees that with all these optimizations we still produce results according to the specification. If in a future commit we for example further improve the runtime performance or the quality of the output mesh, the reviewed specification stays the same and we get correctness with respect to it, without any re-review. Also see how I developed this project only through shaping this specification. Development During development, I controlled only a small specification, leaving the proofs and detailed implementation as a black box to agents. I started with a specification that I estimated was relatively easy to implement and formally prove correct and then grew the requirements. In each of the steps listed below, I had the agent implement and formally prove the specification. This stepwise refinement allowed me to delegate large pieces of work to agents, while getting feedback that my specification is satisfiable and verifying the progress of the agents toward my end goal at each milestone. I instructed agents to first write informal proofs before formalizing. I started by having an agent formalize a paper that provides a mathematical framework for describing solids based on simplicial chains. This gave me a formal existence result without concrete implementation (see CSG/Legacy/ChainIntersectionExistence.lean ). F. R. Feito and M. Rivero, "Geometric modelling based on simplicial chains," Computers & Graphics 22 (5), 611–619 (1998). doi:10.1016/S0097-8493(98)00