이것은 대화형 노트북입니다. 로컬에서 실행하거나 아래 링크를 사용할 수 있습니다:

HuggingFace Datasets를 preprocess_model_input

Note: This is a temporary workaround

이 가이드는 Weave 평가에서 HuggingFace Datasets를 사용하기 위한 해결 방법을 보여줍니다.

이 프로세스를 단순화할 더 원활한 통합을 개발하기 위해 적극적으로 노력하고 있습니다.
이 접근 방식은 작동하지만, 외부 데이터셋 작업을 더 간단하게 만들 향후 개선 및 업데이트를 기대하세요.

설정 및 가져오기

먼저, Weave를 초기화하고 실험 추적을 위해 Weights & Biases에 연결합니다.
!pip install datasets wandb weave
python
# Initialize variables
HUGGINGFACE_DATASET = "wandb/ragbench-test-sample"
WANDB_KEY = ""
WEAVE_TEAM = ""
WEAVE_PROJECT = ""

# Init weave and required libraries
import asyncio

import nest_asyncio
import wandb
from datasets import load_dataset

import weave
from weave import Evaluation

# Login to wandb and initialize weave
wandb.login(key=WANDB_KEY)
client = weave.init(f"{WEAVE_TEAM}/{WEAVE_PROJECT}")

# Apply nest_asyncio to allow nested event loops (needed for some notebook environments)
nest_asyncio.apply()

HuggingFace 데이터셋 로드 및 준비

  • HuggingFace 데이터셋을 로드합니다.
  • 데이터셋 행을 참조하기 위한 인덱스 매핑을 생성합니다.
  • 이 인덱스 접근 방식을 통해 원본 데이터셋에 대한 참조를 유지할 수 있습니다.
Note:
인덱스에서 hf_hub_name와 함께 hf_id를 인코딩하여 각 행에 고유한 식별자가 있는지 확인합니다.
이 고유한 다이제스트 값은 평가 중에 특정 데이터셋 항목을 추적하고 참조하는 데 사용됩니다.
# Load the HuggingFace dataset
ds = load_dataset(HUGGINGFACE_DATASET)
row_count = ds["train"].num_rows

# Create an index mapping for the dataset
# This creates a list of dictionaries with HF dataset indices
# Example: [{"hf_id": 0}, {"hf_id": 1}, {"hf_id": 2}, ...]
hf_index = [{"hf_id": i, "hf_hub_name": HUGGINGFACE_DATASET} for i in range(row_count)]

처리 및 평가 함수 정의

처리 파이프라인

  • preprocess_example: 인덱스 참조를 평가에 필요한 실제 데이터로 변환합니다
  • hf_eval: 모델 출력을 점수화하는 방법을 정의합니다
  • function_to_evaluate: 평가 중인 실제 함수/모델
@weave.op()
def preprocess_example(example):
    """
    Preprocesses each example before evaluation.
    Args:
        example: Dict containing hf_id
    Returns:
        Dict containing the prompt from the HF dataset
    """
    hf_row = ds["train"][example["hf_id"]]
    return {"prompt": hf_row["question"], "answer": hf_row["response"]}

@weave.op()
def hf_eval(hf_id: int, output: dict) -> dict:
    """
    Scoring function for evaluating model outputs.
    Args:
        hf_id: Index in the HF dataset
        output: The output from the model to evaluate
    Returns:
        Dict containing evaluation scores
    """
    hf_row = ds["train"][hf_id]
    return {"scorer_value": True}

@weave.op()
def function_to_evaluate(prompt: str):
    """
    The function that will be evaluated (e.g., your model or pipeline).
    Args:
        prompt: Input prompt from the dataset
    Returns:
        Dict containing model output
    """
    return {"generated_text": "testing "}

평가 생성 및 실행

  • hf_index의 각 인덱스에 대해:
    1. preprocess_example HF 데이터셋에서 해당 데이터를 가져옵니다.
    2. 전처리된 데이터는 다음으로 전달됩니다 function_to_evaluate.
    3. 출력은 다음을 사용하여 점수가 매겨집니다 hf_eval.
    4. 결과는 Weave에서 추적됩니다.
# Create evaluation object
evaluation = Evaluation(
    dataset=hf_index,  # Use our index mapping
    scorers=[hf_eval],  # List of scoring functions
    preprocess_model_input=preprocess_example,  # Function to prepare inputs
)

# Run evaluation asynchronously
async def main():
    await evaluation.evaluate(function_to_evaluate)

asyncio.run(main())