본문 바로가기

명징직조

Prompt Compilerization: Toward Context-Level Optimization in LLM-Assisted Code Generation, 프롬프트 컴파일러화(Prompt Compilerization): LLM 기반 코드 생성의 문맥 수준 최적화를 향하여

Abstract

Large Language Models (LLMs) demonstrate remarkable capabilities in local reasoning and small-scale code synthesis, yet their efficiency degrades as project scope and structural complexity increase.
This paper introduces Prompt Compilerization, a novel paradigm that parallels Relocatable Device Code (RDC) and Device Link-Time Optimization (LTO) mechanisms in CUDA compilation.
By treating prompts as semantic translation units and transforming them into reusable Prompt Intermediate Representations (PIRs), we propose a framework that reduces redundant context, maintains dependency consistency, and enables large-scale reasoning through modular prompt linking and graph-level optimization.


1. Introduction

Current LLM-based programming workflows suffer from context inflation and semantic drift as codebases scale.
While small functions or modules yield high-quality completions, large-scale systems—e.g., AI compilers, deep learning runtimes, or graph executors—require multi-file consistency, long-term memory, and dependency tracking that exceed the effective context length of existing LLMs.

This problem mirrors the pre-RDC CUDA compilation era, where all device functions had to be co-located within a single translation unit.
Just as RDC and LTO allowed modular yet optimizable device code compilation, Prompt Compilerization aims to bring modularity and reuse to LLM prompting.

We formalize an analogy:

LLM prompting can be treated as a semantic compilation process, where prompts correspond to translation units, embeddings act as IR (Intermediate Representation), and semantic linking replaces static context concatenation.


2. Motivation and Background

2.1 Limitations of Traditional Prompting

  • Global Context Bottleneck: All dependencies must fit within the model’s token limit.
  • Redundant Re-encoding: The same contextual definitions (e.g., API specs, math formulas) are repeatedly re-fed.
  • Lack of Linking Semantics: Each session or prompt acts as an isolated translation unit, losing global coherence.
  • Inefficient Reasoning Scaling: Context growth is linear, but reasoning gain saturates rapidly.

2.2 CUDA Analogy: RDC + Device LTO

In CUDA:

  • RDC enables separate compilation of device functions and deferred linking.
  • Device LTO performs optimization at the link-time IR level across translation units.

Prompt Compilerization borrows this paradigm:

  • Modular prompt fragments = Translation units.
  • Semantic embeddings = Device IR.
  • Context linkage and optimization = Device LTO.

3. Proposed Framework: Prompt Compilerization

3.1 Concept Overview

We introduce a three-stage pipeline analogous to code compilation:

CUDA Compilation StagePrompt Compilerization Stage
Source → PTX Prompt → Prompt IR (PIR)
PTX Linking (RDC) PIR Linking (Context Graph Assembly)
Device LTO Optimization Semantic Graph Optimization (S-LTO)

3.2 Stage 1 — Prompt IR Generation (Pre-Compilation)

Each prompt or document fragment is converted into a Prompt Intermediate Representation (PIR) via:

  1. Semantic Embedding (vector form, akin to IR instructions).
  2. Dependency Extraction (graph edges: imports, APIs, variable scopes).
  3. Contextual Compression (removal of redundant or verbose expressions).

PIR thus serves as a lossy but semantically dense representation of the prompt — similar to how PTX or NVVM IR represents device logic abstractly.


3.3 Stage 2 — PIR Linking (Context Graph Assembly)

At query time, only relevant PIRs are linked:

  • Dependencies are resolved like symbol linking in compiled binaries.
  • Unused fragments are ignored (semantic dead-code elimination).
  • Redundant contexts (identical definitions, repeated imports) are unified.

This allows the LLM to operate on a minimal linked context graph instead of a raw concatenated prompt.


3.4 Stage 3 — Semantic LTO (S-LTO)

Analogous to CUDA’s Device Link-Time Optimization, S-LTO performs cross-fragment optimization:

  • Inlining of frequent semantic units.
  • Removal of redundant constraints.
  • Cross-module reasoning propagation.

In implementation terms, S-LTO corresponds to a lightweight transformer operating over PIR graphs, merging overlapping embeddings and retaining only essential edges.


4. Experimental Analogy: Graph Capture & Context Reuse

If a CUDA Graph Capture represents a static graph of executable kernels,
then Prompt Compilerization introduces Prompt Graph Capture:

  • Capturing the semantic graph of a prompt flow.
  • Reusing this graph for future LLM calls.
  • Allowing graph replay with parameter substitution, much like kernel graph replay.

This yields a reusable, deterministic “execution graph” of reasoning.


5. Advantages

  1. Prompt Length Reduction: Modular compilation avoids repeated definitions.
  2. Consistency Across Sessions: Linked IRs preserve global invariants.
  3. Scalable Reasoning: Enables multi-file or multi-module reasoning without exceeding context windows.
  4. Cross-Prompt Optimization: Shared semantics (e.g., common math, API specs) are deduplicated.
  5. Graph-Capture Compatibility: Facilitates integration with structured AI toolchains (e.g., AI compilers, trainers).

6. Limitations and Future Work

  • PIR Standardization: A universal semantic IR format for LLMs is needed.
  • Dynamic Linking Cost: Late linking introduces latency; caching strategies must be optimized.
  • Version Drift: IR fragments must remain consistent across evolving model versions.
  • Security and Privacy: Compiled prompts may inadvertently expose compressed sensitive context.

Future research directions:

  • Differentiable Prompt Linking: Learnable PIR graphs optimized via meta-learning.
  • Prompt Auto-Scheduler: Analogous to TVM’s kernel planner—automatically selecting optimal prompt graphs for given tasks.
  • Contextual JIT Compiler: On-demand compilation of semantic fragments similar to runtime codegen.

7. Conclusion

We propose a new conceptual framework—Prompt Compilerization—that redefines prompting as a compilation process rather than a linear instruction feed.
By adopting principles from CUDA’s RDC + Device LTO and Graph Capture, it becomes possible to modularize, link, and optimize semantic context at scale.
This bridges the gap between token-level prompting and system-level reasoning, marking a step toward graph-aware, compiler-optimized LLM architectures.

 

초록(Abstract)

대규모 언어 모델(LLM)은 국소적 추론(local reasoning)소규모 코드 생성에서는 탁월한 성능을 보이지만,
프로젝트의 구조가 커지고 복잡도가 증가함에 따라 효율성이 급격히 저하된다.

본 논문은 CUDA 컴파일의 Relocatable Device Code(RDC)Device Link-Time Optimization(LTO) 메커니즘을 기반으로 한
새로운 패러다임 **“프롬프트 컴파일러화(Prompt Compilerization)”**를 제안한다.

우리는 프롬프트를 **의미적 번역 단위(Semantic Translation Unit)**로 취급하고, 이를 재사용 가능한 Prompt Intermediate Representation (PIR) 형태로 변환함으로써,
중복된 문맥을 제거하고, 종속성 일관성을 유지하며, 대규모 추론을 모듈형 링크 및 그래프 수준 최적화를 통해 가능하게 하는 구조를 제안한다.


1. 서론 (Introduction)

현재의 LLM 기반 프로그래밍 워크플로우는 코드베이스가 확장될수록 문맥 팽창(context inflation)의미적 일관성 손실(semantic drift) 문제를 겪는다.
함수나 커널과 같은 소규모 단위에서는 높은 정확도의 결과를 내지만,
딥러닝 런타임, 그래프 실행기(Graph Executor), AI 컴파일러 등과 같은 대규모 시스템 수준에서는
여러 파일 간의 일관성과 장기적 상태 추적이 필요해지며, 이는 기존 LLM의 컨텍스트 길이를 넘어선다.

이 현상은 RDC 이전의 CUDA 빌드 구조와 유사하다.
당시에는 모든 device 함수를 단일 번역 단위에 통합해야 했기 때문에 대규모 최적화가 불가능했다.
RDC 및 LTO의 등장으로 모듈별 컴파일이 가능해지고, 링크 시점에서의 전역 최적화가 실현되었다.

본 논문은 이 개념을 LLM으로 확장한다.
즉, **프롬프트를 하나의 “컴파일 단위”로 보고, 의미 수준의 IR로 변환하여 링크 및 최적화할 수 있는 “프롬프트 컴파일러화”**를 제안한다.


2. 배경 및 문제 정의 (Background and Motivation)

2.1 기존 프롬프트 방식의 한계

  • 전역 문맥 병목: 모든 종속 정보를 한 번에 입력해야 하므로, 토큰 한계에 즉시 도달한다.
  • 중복 인코딩: 동일한 설명(API, 수학식, 구조 정의)을 반복 입력해야 한다.
  • 링크 개념 부재: 프롬프트 간 의미적 연결이 불가능하여 세션 단위의 일회성 사용으로 끝난다.
  • 비선형 확장 한계: 문맥 길이는 선형적으로 증가하지만, 추론 효율은 포화된다.

2.2 CUDA의 RDC + Device LTO와의 유사성

CUDA에서 RDC는 여러 .cu 파일을 분리 컴파일 후 재링크할 수 있게 하고,
Device LTO는 링크 시점에서 IR 레벨 최적화를 수행한다.

이 구조는 프롬프트의 효율화에도 직접적으로 대응된다.
즉,

  • “모듈형 프롬프트 단편(Fragment)” → Translation Unit
  • “의미 임베딩(embedding)” → Device IR
  • “문맥 링크 및 최적화” → Device LTO

3. 제안하는 프레임워크: 프롬프트 컴파일러화 (Prompt Compilerization Framework)

3.1 개요

CUDA 컴파일 과정과의 대응은 다음과 같다.

CUDA 단계프롬프트 컴파일러화 단계
소스 → PTX 프롬프트 → Prompt IR (PIR)
PTX 링크(RDC) PIR 링크 (Context Graph 조립)
Device LTO 의미 그래프 최적화 (S-LTO)

3.2 1단계 — Prompt IR 생성 (Pre-Compilation)

각 프롬프트 조각을 Prompt Intermediate Representation (PIR) 으로 변환한다.
이 과정은 다음의 세 단계를 포함한다.

  1. 의미 임베딩(Semantic Embedding) — 문맥을 벡터화하여 추상 의미 단위로 표현
  2. 종속성 추출(Dependency Extraction) — 모듈, API, 변수 범위 등의 관계 그래프화
  3. 문맥 압축(Contextual Compression) — 불필요한 서술 및 반복 제거

결과적으로 PIR은 **손실 압축된 의미적 중간 표현(IR)**로, PTX나 NVVM IR과 동일한 역할을 수행한다.


3.3 2단계 — PIR 링크 (Context Graph Assembly)

질의 시점에 필요한 PIR만 선택적으로 링크한다.

  • 종속성 해결(symbol resolution)
  • 불필요한 PIR 제거(dead semantic elimination)
  • 중복된 정의 병합(duplicate unification)

이 과정을 통해 LLM은 원시 텍스트 프롬프트가 아닌, 최소 링크 그래프 형태의 컨텍스트로 추론을 수행할 수 있다.


3.4 3단계 — 의미적 LTO (S-LTO, Semantic Link-Time Optimization)

CUDA의 Device LTO처럼, S-LTO는 PIR 간 의미적 교차 최적화를 수행한다.

  • 자주 참조되는 단위의 인라인 처리
  • 반복 문맥의 제거
  • 모듈 간 의미 전파 (cross-module reasoning propagation)

이 단계는 일종의 “프롬프트 그래프 최적화기”로, 의미 그래프를 경량화하고 정합성을 강화한다.


4. 그래프 캡처 및 컨텍스트 재사용 (Graph Capture & Context Reuse)

CUDA의 Graph Capture가 커널 실행 흐름을 고정하여 재사용하듯,
Prompt Compilerization에서는 Prompt Graph Capture를 수행한다.

  • 프롬프트 흐름을 의미 그래프로 캡처
  • 동일 질의 재사용 시 그래프 리플레이 (graph replay)
  • 일부 파라미터만 교체 가능 (prompt parameterization)

이 방식은 반복적 프롬프트 호출의 일관성과 재현성을 보장한다.


5. 장점 (Advantages)

  1. 문맥 길이 절감: 중복 정의 제거를 통해 입력 토큰 수 감소
  2. 세션 간 일관성 확보: 링크된 PIR이 전역 불변성을 유지
  3. 확장 가능한 추론: 대규모 코드베이스에서도 맥락 손실 없이 작동
  4. 교차 프롬프트 최적화: 동일한 개념(API, 수식 등) 재사용
  5. 그래프 실행기 호환성: Graph Capture-safe 구조와 자연스럽게 결합 가능

6. 한계점 및 향후 연구 과제 (Limitations and Future Work)

  • PIR 표준화: LLM 간 호환 가능한 IR 형식 정의 필요
  • 동적 링크 비용: 링크 시점 지연(latency) 발생 가능성
  • 버전 호환성 문제: 모델 버전에 따른 PIR 의미 변화
  • 보안 이슈: 압축된 문맥에 민감 정보가 포함될 위험

향후 연구 방향

  1. Differentiable Prompt Linking: 메타학습 기반의 자동 링크 최적화
  2. Prompt Auto-Scheduler: TVM과 유사한 최적 프롬프트 그래프 선택기
  3. Contextual JIT Compiler: 런타임 시점의 온디맨드 의미 컴파일

7. 결론 (Conclusion)

본 논문은 LLM 프롬프트를 단순한 텍스트 입력이 아닌 컴파일 가능한 의미 단위로 재정의하였다.
CUDA의 RDC + LTO 개념과 Graph Capture 구조를 차용하여,
모듈형 프롬프트, 의미적 링크, 그래프 최적화를 통해 대규모 추론의 효율성과 일관성을 확보하는 새로운 관점을 제시했다.

이는 단순한 “프롬프트 엔지니어링”을 넘어,
프롬프트를 컴파일하고 링크하며 최적화하는 “Prompt Compiler” 시대의 초석이 될 것이다.