1.4. RunnableParallel

RunnableParallel은 LangChain에서 제공하는 주요 컴포지션 프리미티브 중 하나로, 여러 개의 Runnable을 병렬적으로 실행할 수 있도록 설계된 클래스입니다. 이 클래스는 동일한 입력 데이터를 여러 Runnable에 동시에 전달하여 독립적으로 처리한 후, 각 결과를 매핑하여 반환합니다.

특징 및 주요 기능

  • 병렬 실행: 여러 Runnable을 동시에 실행하여 처리 속도를 높일 수 있습니다.
  • 입력 공유: 동일한 입력 데이터를 모든 Runnable에 전달합니다.
  • 결과 매핑: 각 Runnable의 출력값을 키-값 쌍으로 반환합니다.
  • 유연한 설정: 딕셔너리 형태로 Runnable을 정의하거나, 파이프 연산자(|)를 사용해 손쉽게 구성할 수 있습니다.

사용 방법

1. 기본 사용 예제

아래는 숫자를 처리하는 세 가지 함수(add_one, mul_two, mul_three)를 병렬로 실행하는 예제입니다:

from langchain_core.runnables import RunnableLambda, RunnableParallel

# 함수 정의
def add_one(x: int) -> int:
   return x + 1

def mul_two(x: int) -> int:
   return x * 2

def mul_three(x: int) -> int:
   return x * 3

# Runnable 생성
runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
runnable_3 = RunnableLambda(mul_three)

# RunnableParallel로 병렬 실행 설정
parallel_runnable = RunnableParallel(
   mul_two=runnable_2,
   mul_three=runnable_3
)

# 실행
result = parallel_runnable.invoke(1)
print(result)
{‘mul_two’: 2, ‘mul_three’: 3}

2. LLM과 함께 사용

아래는 LangChain의 LLM을 활용해 병렬로 joke, poem, question을 생성하는 예제입니다:

from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
from langchain_core.runnables import RunnableParallel
from langchain_core.output_parsers import StrOutputParser

# Prompt 정의
joke_template = ChatPromptTemplate.from_template("tell me a joke about {topic}")
poem_template = ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
question_template = ChatPromptTemplate.from_template("make a question about {topic}")

# 모델 및 파서 정의
model = ChatOllama(model='exaone3.5')
parser = StrOutputParser()

# Chain 정의
joke_chain = joke_template | model | parser
poem_chain = poem_template | model | parser
question_chain = question_template | model | parser

# RunnableParallel 설정
parallel_chains = RunnableParallel(
   joke=joke_chain,
   poem=poem_chain,
   question=question_chain
)

# 실행
output = parallel_chains.invoke({"topic": "snowman"})
print(output)
{‘joke’: ‘Sure, here\’s a snowy joke for you:\n\nWhy don\’t snowmen ever get lost?\n\nBecause they always have a carrot-towards home! (get it? Carrot as in the vegetable, play on words with “course to” towards)\n\nHope that brings a smile to your face! ❄️😄’, ‘poem’: “Carved in winter’s chill, smiles bright beneath falling snow,  \nCozy coal eyes watch as icy drifts softly grow.”, ‘question’: “Here’s a fun question about snowmen:\n\n**What unique feature can you add to a snowman to make it look extra festive during the holiday season?**\n\n(Possible answers could include carrot noses, coal eyes and mouths, scarf made of yarn, or even a small hat adorned with bells!)”}

실행 방식 비교

병렬 처리를 통해 개별적으로 실행했을 때보다 더 빠르게 작업을 완료할 수 있습니다. 아래는 동일한 작업을 병렬 처리와 개별 처리로 실행했을 때의 시간 비교 예제입니다:

  • 개별 처리 시간:
    • Joke Chain: 약 11초
    • Poem Chain: 약 0.9초
    • Question Chain: 약 0.75초
  • 병렬 처리 시간: 약 0.92초

응용 사례

  1. 다중 작업 병렬화: 동일한 입력 데이터로 여러 작업(예: 텍스트 생성, 분석 등)을 동시에 수행.
  2. 독립적인 체인 실행: 서로 다른 입력 데이터를 사용하는 체인을 병렬로 실행하여 결과를 통합.

RunnableParallel은 LangChain에서 작업 효율성을 극대화하기 위한 강력한 도구입니다. 특히, 다중 작업을 동시에 처리해야 하는 경우 유용하며, 간단한 인터페이스와 유연한 설정으로 다양한 시나리오에 적용 가능합니다

이 글은 카테고리: 랭체인 (LangChain)에 포함되어 있으며 태그: (이)가 사용되었습니다. 고유주소를 북마크하세요.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다