In-Context Learning은 프롬프트 안의 설명과 예시를 이용해 작업을 수행하는 현상이다. 추가 파라미터 학습 없이 입력 구성에 따라 결과가 달라진다는 점에서 예시의 선택과 순서가 중요해진다.

예시를 바꿨을 때

같은 작업에서도 예시의 관련성, 순서와 라벨 표현에 따라 답변이 달라질 수 있다. 예시를 몇 개 넣었는지뿐 아니라 어떤 작업 규칙을 보여 주었는지 확인한다.

좋은 결과가 나왔다고 모델이 의도한 규칙을 사용했다고 바로 결론 내리지는 않는다. 새로운 표현의 입력에서도 동작이 유지되는지 보고 입력 패턴이나 기존 지식을 이용한 경우와 구분한다.

서로 다른 설명 관점

ICL을 설명하는 관점에는 회귀 함수 학습, 메타 최적화, 베이지안 해석과 기계적 해석이 있다. 서로 다른 가정과 실험에서 나온 설명이므로 어떤 모델과 작업을 설명하는지 맞춰 읽는다.

이론 모델에서 성립한 결과와 대규모 언어 모델에서 관찰한 현상은 적용 범위가 다를 수 있다. 어떤 모델과 작업에서 얻은 설명인지 함께 읽어야 한다.

프롬프트 비교의 조건

평가 입력을 고정하고 예시 선택·순서·수를 나눠 바꾼다. 같은 예시라도 입력과 가까운 경우와 다른 유형의 경우를 나눠 보면 모델이 어떤 단서를 사용하는지 살펴볼 수 있다. 라벨을 바꾸거나 불필요한 문맥을 넣는 실험은 작업 규칙과 표면 패턴의 영향을 구분하는 데 쓰인다.

코드와 수식 메모 (5개)

이전에 정리한 코드와 수식이다. 개념을 읽기 위한 예시이며, 논문 저자의 공식 구현이나 현재 버전에서 실행되는 사용법과 일치하는지는 별도로 확인해야 한다.

`D ∼ P(X,Y), Q ∼ PQ
 ← Fθ(D, Q)
성능 측정: S = ED,Q,A[M(A, Â)]`
`D = {(xi, f(xi))}ⁿᵢ₌₁ (f는 linear function class에서 샘플링)
A = {f(qj)}ᵐⱼ₌₁ (corresponding function values)`
`# ICL Performance Measurement
def evaluate_icl_performance(model, demonstration, query, gold_labels):
    """
    ICL 성능 평가를 위한 기본 framework
    """
    # Demonstration과 Query concatenation
    context = format_context(demonstration, query)

    # Model prediction
    predictions = model.generate(context)

    # Performance metric calculation
    performance = calculate_metric(predictions, gold_labels)

    return performance

def format_context(demonstration, query):
    """
    Demonstration과 query를 적절한 format으로 구성
    """
    context = ""
    for example in demonstration:
        context += f"Input: {example['input']}\nOutput: {example['output']}\n"

    context += f"Input: {query}\nOutput:"
    return context`
`# Demonstration Order Selection
def optimize_demonstration_order(examples, model, validation_set):
    """
    Demonstration order 최적화를 위한 permutation search
    """
    from itertools import permutations

    best_order = None
    best_performance = 0

    # All possible permutation 탐색 (작은 demonstration set에 대해)
    for order in permutations(examples):
        performance = evaluate_order(order, model, validation_set)
        if performance > best_performance:
            best_performance = performance
            best_order = order

    return best_order, best_performance

def evaluate_order(demonstration_order, model, validation_set):
    """
    특정 demonstration order에 대한 성능 평가
    """
    total_performance = 0
    for val_example in validation_set:
        performance = evaluate_icl_performance(
            model, demonstration_order, val_example['query'], val_example['label']
        )
        total_performance += performance

    return total_performance / len(validation_set)`
`# Induction Head Detection
def analyze_attention_patterns(model, input_sequence):
    """
    Induction head pattern 분석을 위한 attention visualization
    """
    # Attention weight extraction
    with torch.no_grad():
        outputs = model(input_sequence, output_attentions=True)
        attentions = outputs.attentions

    # Induction pattern detection
    induction_scores = []
    for layer_idx, layer_attention in enumerate(attentions):
        # Previous token -> current token attention pattern 분석
        induction_score = detect_induction_pattern(layer_attention)
        induction_scores.append(induction_score)

    return induction_scores

def detect_induction_pattern(attention_weights):
    """
    Attention weight에서 induction pattern 탐지
    """
    # Simplified induction pattern detection logic
    # 실제 구현에서는 더 sophisticated algorithm 필요
    pattern_strength = calculate_pattern_strength(attention_weights)
    return pattern_strength`

참고자료

티스토리에 쓴 글을 이곳의 문체와 구성에 맞춰 다시 정리했습니다. 원문 보기 ↗ 원문에 포함된 일부 이미지와 서식은 원문 링크에서 확인할 수 있습니다.