distilabel로 수학 선호도 데이터셋 만들기
distilabel로 수학 선호도 데이터셋 만들기 (Create a Mathematical Preference Dataset with distilabel)
distilabel로 여러 Mistral 모델을 사용해 수학 선호도(preference) 합성 데이터셋을 만드는 방법을 배우는 문서예요. 작성자는 [Argilla]의 David Berenstein와 Sara Han Díaz입니다.
출처: 문서
본문
이 튜토리얼에서는 distilabel로 다양한 Mistral 모델을 사용해 수학 선호도 합성 데이터셋을 만드는 방법을 배워요.
[distilabel]은 LLM으로 데이터셋을 생성·라벨링할 수 있는 AI Feedback(AIF) 프레임워크로, 다양한 사용 사례에 활용돼요. 견고성·효율성·확장성을 고려해 구현되어 누구나 여러 시나리오에서 쓸 수 있는 합성 데이터셋을 만들 수 있게 해줍니다.
distilabel로는 필요한 여러 단계를 Pipeline으로 구축할 수 있고, 이 단계들은 방향성 비순환 그래프(DAG, Direct Acyclic Graph)의 노드로 연결돼요. 이 튜토리얼에서는 self-instruct 방식을 사용해 지시문(instruction)을 생성한 뒤, MistralAI 모델들로 두 개의 가능한 답변을 생성해요. 그다음 더 높은 수준의 모델(mistral-large)로 답변을 평가합니다. 마지막으로 argilla 패키지로 데이터셋을 분석하고 HF로 푸시해요. 만들 데이터셋의 예시는 [여기]에서 확인할 수 있어요.
다음 단계를 따를게요:
- 시드 데이터(seed data) 지정
Pipeline의 구성 요소 정의- 파이프라인 실행
- (선택) argilla로 데이터셋 어노테이션/분석
시작하기 (Getting Started)
distilabel을 실행하는 데 필요한 의존성을 먼저 설치해요. 데이터 생성용 mistralai 통합과 데이터셋 분석용 argilla 패키지 같은 추가 기능(extras)도 필요해요.
!pip install distilabel[mistralai,argilla]==1.1.1
필요한 임포트를 해요.
from distilabel.llms import MistralLLM
from distilabel.pipeline import Pipeline
from distilabel.steps import ExpandColumns, LoadDataFromDicts, CombineColumns, PreferenceToArgilla
from distilabel.steps.tasks import TextGeneration, UltraFeedback, SelfInstruct
from distilabel.steps.formatting.dpo import FormatTextGenerationDPO
MistralAI 모델을 사용하려면 API 키도 필요해요. [MistralAI]에 로그인해 API Keys에서 활성화할 수 있어요.
추가로 argilla로 데이터를 시각화·어노테이션하려면 데이터셋이 푸시될 [Hugging Face Space]를 실행해야 해요. 자세한 내용은 [Argilla 문서]를 확인하세요. 설정 후에는 ARGILLA_API_URL(https://[your-owner-name]-[your_space_name].hf.space 형태)과 ARGILLA_API_KEY(Space의 My Settings에서 확인)를 지정해야 해요.
키가 새지 않도록 시스템 환경 변수로 설정하거나, Google Colab이라면 secret으로 추가하는 걸 권장해요.
import os
# Environment variable
os.environ['MISTRAL_API_KEY'] = '<MISTRAL_API_KEY>'
os.environ['ARGILLA_API_URL'] = '<ARGILLA_API_URL>'
os.environ['ARGILLA_API_KEY'] = '<ARGILLA_API_KEY>'
# Environment variable in Google Colab with secrets
os.environ['MISTRAL_API_KEY'] = userdata.get('MISTRAL_API_KEY')
os.environ['ARGILLA_API_URL'] = userdata.get('ARGILLA_API_URL')
os.environ['ARGILLA_API_KEY'] = userdata.get('ARGILLA_API_KEY') # by default, owner.apikey
시드 데이터 지정 (Indicate the Seed Data)
수학 주제 목록인 시드 데이터를 지정해 지시문을 만들어요. 소개 목적으로 처음 10개 샘플만 사용할게요. 이 숫자를 바꿔 더 적거나 많은 데이터를 생성할 수 있어요.
math_topics = [
"Algebraic Expressions",
"Linear Equations",
"Quadratic Equations",
"Polynomial Functions",
"Rational Expressions",
"Exponential Functions",
"Logarithmic Functions",
"Sequences and Series",
"Matrices",
"Determinants",
"Complex Numbers",
"Trigonometry",
"Geometry",
"Coordinate Geometry",
"Vector Algebra",
"Statistics",
"Probability",
"Calculus",
"Differential Calculus",
"Integral Calculus",
"Limits and Continuity",
"Differentiation",
"Integration",
"Theorems of Calculus",
"Mathematical Reasoning",
"Set Theory",
"Number Theory",
"Permutations and Combinations",
"Binomial Theorem",
"Arithmetic Progressions",
"Geometric Progressions",
"Harmonic Progressions",
"Trigonometric Ratios",
"Trigonometric Identities",
"Inverse Trigonometric Functions",
"Hyperbolic Functions",
"Conic Sections",
"Circle Geometry",
"Ellipse Geometry",
"Parabola Geometry",
"Hyperbola Geometry",
"Function Theory",
"Graph Theory",
"Differential Equations",
"Mathematical Induction",
"Discrete Mathematics",
]
data=[{"input": topic} for topic in math_topics[:10]]
구성 요소 정의 (Defining the Building Blocks)
기본 정보는 [여기]의 일반 문서를 확인하세요: [Pipeline 문서], [Steps 문서], [Tasks 문서], [LLMs 문서].
이 경우 이름 mistral-pipe와 설명을 붙여 컨텍스트 매니저로 Pipeline을 만들어요. 각 단계를 살펴볼게요:
load_dataset: 사전 리스트인 데이터를 로드해요. 입력·출력 열(column)은input으로 같아요.self_instruct_open_mistral:SelfInstruct는 미리 정의된 작업으로, 지시문 수, 쿼리 생성 기준, 애플리케이션 설명, 입력이 주어지면 새 쿼리를 생성해요. 기본 기준과open-mistral-7b를 사용할게요. 입력 열은input, 출력 열은instructions(각 입력당 지시문 리스트, 기본 5개)와model_name이에요.expand_columns: 답변을 생성하려면instructions리스트의 각 지시문을 개별적으로 사용해야 해요. 이 단계는instructions열을instruction아래 여러 행으로 확장해요.generate_open-mistral-7b와generate_open-mixtral-8x7b: 두 오픈소스 모델(open-mistral-7b,open-mixtral-8x7b)로 기본TextGeneration작업을 사용해 답변을 생성해요. 둘을 동시에 실행할 수 있어요. 각 단계의 입력 열은instruction, 출력 열은generation과model_name이에요.combine_generations: 두 모델의 생성물과 이름을 단일 열generations로 결합해요.ultrafeedback_mistral-large-latest: 마지막으로 클로즈드 모델mistral-large로UltraFeedback을 사용해 답변을 평가하며, 특정 측면 대신overall-rating을 요청해요. 입력 열은input과generations, 출력 열은ratings,rational,model_name이에요.- (선택)
to_argilla: 이 데이터를 선호도 데이터로argilla에 어노테이션하도록 보내 데이터 품질을 개선할 수 있어요. 필요한 열은input,model_names,instructions,instruction,generations,model_name,ratings,rationales예요. 앞서 말한 대로 데이터셋이 푸시·시각화될 실행 중인 [Hugging Face Space]가 필요해요. format_dpo:FormatTextGenerationDPO로chosen과rejected열로 DPO용 데이터셋을 쉽게 준비할 수 있어요.
마지막으로 남은 것은 위 단계들을 >>로 연결하는 것뿐이에요. to_argilla 단계를 건너뛰려면 파이프라인에서 주석 처리하고 연결된 단계에서 제거하면 돼요.
with Pipeline(name="mistral-pipe", description="A pipeline to generate and score a distiset") as pipeline:
load_dataset = LoadDataFromDicts(
name= "load_dataset", data=data,
)
self_instruct_open_mistral = SelfInstruct(
name="self_instruct_open_mistral", llm=MistralLLM(model="open-mistral-7b"),
)
expand_columns = ExpandColumns(
name="expand_columns", columns={"instructions": "instruction"}
)
tasks = []
for llm in (MistralLLM(model="open-mistral-7b"),
MistralLLM(model="open-mixtral-8x7b")
):
tasks.append(
TextGeneration(name=f"generate_{llm.model_name}", llm=llm)
)
combine_generations = CombineColumns(
name="combine_generations",
columns=["generation", "model_name"],
output_columns=["generations", "model_names"],
)
ultrafeedback_mistral_large = UltraFeedback(
name= "ultrafeedback_mistral_large", llm=MistralLLM(model="mistral-large-latest"), aspect="overall-rating"
)
to_argilla = PreferenceToArgilla(
dataset_name="mathematical-dataset",
dataset_workspace="admin", # by default
num_generations=2
)
format_dpo = FormatTextGenerationDPO(name="format_dpo")
load_dataset >> self_instruct_open_mistral >> expand_columns >> tasks >> combine_generations >> ultrafeedback_mistral_large >> [to_argilla, format_dpo]
파이프라인 실행 (Run the Pipeline)
마지막으로 run 메서드로 파이프라인을 실행해요. 각 단계를 추가로 커스터마이즈하기 위해 일부 런타임 파라미터를 설정할 수 있어요. 전체 실행은 약 10분 정도 걸립니다. 파이프라인을 테스트하려면 run 대신 단일 배치를 사용하는 dry_run 메서드를 쓸 수 있어요.
distiset = pipeline.run(
parameters={
"generate_open-mistral-7b": {
"llm": {
"generation_kwargs": {
"max_new_tokens": 512,
"temperature": 0.7,
}
}
},
"generate_open-mixtral-8x7b": {
"llm": {
"generation_kwargs": {
"max_new_tokens": 512,
"temperature": 0.7,
}
}
}
}
)
그리고 그게 다예요! distilabel로 MistralAI 모델들로 합성 데이터셋을 만들었어요.
distiset
🤗 데이터셋을 HF로 푸시하고 공유해 보세요.
distiset.push_to_hub(repo_id="<repository_name>/math-preference-dataset")
Argilla에 추가했다면 어노테이션 과정을 시작해 데이터셋 품질을 개선할 수 있어요.
결론 (Conclusion)
이 튜토리얼에서는 distilabel로 MistralAI 모델들을 사용해 합성 데이터셋을 만드는 방법을 배웠어요. self_instruct 작업으로 지시문을 생성하고, 두 개의 서로 다른 MistralAI 모델로 답변을 생성했어요. 마지막으로 mistral-large 모델로 답변을 평가했죠. 또한 argilla 패키지로 데이터셋을 분석하고 HF로 푸시하는 방법도 봤어요.
🚀 파이프라인을 자유롭게 가지고 놀며 자신만의 합성 데이터셋을 만들어 보세요!
기타 참고 자료: