MemAgent는 긴 문서를 구간별로 읽으며 메모리를 갱신하는 접근이다. 전체 문서를 한 번에 넣는 대신 다음 구간으로 무엇을 전달할지 결정하는 흐름으로 읽었다.

구간 사이의 상태

각 구간 뒤에 유지할 정보를 정리해 다음 구간과 함께 사용한다. 메모리는 모든 문장을 보관하는 저장소가 아니라 후속 처리로 전달하는 상태다.

앞에서 제외한 정보가 나중에 필요할 수 있다. 문서 길이만 늘리는 평가와 특정 근거를 찾아 답하는 평가를 구분해야 하는 이유다.

여러 대화와 학습

Multi-Conversation DAPO는 여러 대화로 나뉜 처리에서 메모리 갱신을 학습하는 구성이다. 각 구간의 독립적인 호출이 이전 메모리를 받고 새 메모리를 반환하므로, 대화가 바뀌어도 상태가 다음 구간에 이어진다.

선형 처리라는 설명만으로 전체 비용을 정할 수는 없다. 구간 수와 구간별 호출, 메모리 길이와 출력 길이를 함께 확인한다.

보고된 결과의 범위

학습 길이와 평가 길이, 필요한 정보가 놓인 위치를 기록해야 비교할 수 있다. 긴 입력의 성공을 정보 손실 없는 무제한 기억으로 해석하지 않는다.

전체 문서 길이가 늘어날수록 읽을 구간 수가 늘고 각 단계는 제한된 메모리를 다음 단계에 전달한다. 학습은 이 갱신 정책이 긴 입력에서도 필요한 정보를 남기도록 조정하는 역할을 한다.

코드와 수식 메모 (8개)

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

`p(x₁:N) = Σ[m₁:K₋₁] ∏[k=1 to K] p(cₖ | mₖ₋₁) · p(mₖ | cₖ, mₖ₋₁)
                                    read         write
`
`Âᵢ,ⱼ,t = rᵢ - mean({Rᵢ}ᴳᵢ₌₁)
`
`JDAPO(θ) = E[1/Σᴳᵢ₌₁Σⁿⁱⱼ₌₁|oᵢ,ⱼ| · Σᴳᵢ₌₁Σⁿⁱⱼ₌₁Σ|oᵢ,ⱼ|t₌₁ [Cᵢ,ⱼ,t - βDKL(πθ||πref)]]
`
`R(ŷ, Y) = max[y∈Y] I(is_equiv(y, ŷ))
`
`R(ŷ, Y) = |{y ∈ Y | I(y ∈ ŷ)}| / |Y|
`
`# Core MemAgent Processing Loop
def memagent_process(document, query, model, chunk_size=5000, memory_size=1024):
    """
    MemAgent의 핵심 processing workflow 구현
    """
    # Document를 chunk로 분할
    chunks = split_document(document, chunk_size)

    # Memory 초기화
    memory = ""

    # Context Processing Phase
    for chunk in chunks:
        context = format_context_processing(query, memory, chunk)

        # Memory update through model generation
        updated_memory = model.generate(
            context,
            max_tokens=memory_size,
            temperature=0.1
        )
        memory = updated_memory

    # Answer Generation Phase
    final_context = format_answer_generation(query, memory)
    answer = model.generate(final_context, max_tokens=1024)

    return answer, memory
def format_context_processing(query, memory, chunk):
    """Context processing template formatting"""
    return f"""You are presented with a problem, a section of an article that may contain the answer, and a previous memory. Please read the section carefully and update the memory with new information that helps to answer the problem, while retaining all relevant details from the previous memory.

<problem> {query} </problem>
<memory> {memory} </memory>
<section> {chunk} </section>

Updated memory:"""

def format_answer_generation(query, memory):
    """Answer generation template formatting"""
    return f"""You are presented with a problem and a previous memory. Please answer the problem based on the previous memory and put the answer in \\boxed {{}}.

<problem> {query} </problem>
<memory> {memory} </memory>

Your answer:"""
`
`# Multi-Conversation DAPO Implementation
class MultiConvDAPO:
    def __init__(self, policy_model, ref_model, kl_coeff=1e-3):
        self.policy_model = policy_model
        self.ref_model = ref_model
        self.kl_coeff = kl_coeff

    def compute_multi_conv_loss(self, queries, conversations_batch, rewards):
        """
        Multi-conversation DAPO loss 계산
        """
        total_loss = 0
        total_tokens = 0

        for i, (query, conversations, reward) in enumerate(
            zip(queries, conversations_batch, rewards)
        ):
            # Group normalization for advantage
            group_rewards = [rewards[j] for j in range(len(rewards))]
            advantage = reward - np.mean(group_rewards)

            # Process each conversation in the sample
            for conv in conversations:
                conv_loss = self.compute_conversation_loss(
                    query, conv, advantage
                )
                total_loss += conv_loss * len(conv)
                total_tokens += len(conv)

        return total_loss / total_tokens

    def compute_conversation_loss(self, query, conversation, advantage):
        """Single conversation loss computation"""
        # Compute importance sampling ratio
        policy_logprobs = self.policy_model.get_logprobs(query, conversation)
        ref_logprobs = self.ref_model.get_logprobs(query, conversation)

        ratio = torch.exp(policy_logprobs - ref_logprobs)

        # Clipped objective
        clip_low, clip_high = 0.8, 1.2
        clipped_ratio = torch.clamp(ratio, clip_low, clip_high)

        # Policy loss with KL penalty
        policy_loss = -torch.min(
            ratio * advantage,
            clipped_ratio * advantage
        ).mean()

        kl_penalty = torch.mean(ref_logprobs - policy_logprobs)

        return policy_loss + self.kl_coeff * kl_penalty
`
`# RULER Benchmark Evaluation
def evaluate_ruler_performance(model, test_suite, context_lengths):
    """
    RULER benchmark에서 MemAgent 성능 평가
    """
    results = {}

    for context_length in context_lengths:
        length_results = {}

        # NIAH variants
        niah_tasks = ['single_key', 'multi_key', 'multi_value', 'multi_query']
        for task in niah_tasks:
            accuracy = evaluate_niah_task(model, test_suite[task], context_length)
            length_results[f'niah_{task}'] = accuracy

        # Variable tracking
        vt_accuracy = evaluate_variable_tracking(
            model, test_suite['variable_tracking'], context_length
        )
        length_results['variable_tracking'] = vt_accuracy

        # Frequent words extraction
        fwe_accuracy = evaluate_frequent_words(
            model, test_suite['frequent_words'], context_length
        )
        length_results['frequent_words'] = fwe_accuracy

        # QA tasks
        qa_accuracy = evaluate_qa_task(
            model, test_suite['qa'], context_length
        )
        length_results['qa'] = qa_accuracy

        results[context_length] = length_results

    return results

def evaluate_niah_task(model, task_data, context_length):
    """Needle-in-a-Haystack task evaluation"""
    correct = 0
    total = len(task_data)

    for sample in task_data:
        # Generate context with specified length
        context = generate_niah_context(sample, context_length)

        # Process with MemAgent
        answer, _ = memagent_process(
            context, sample['query'], model
        )

        # Verify answer
        if verify_answer(answer, sample['ground_truth']):
            correct += 1

    return (correct / total) * 100
`

참고자료

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