다음을 통해 공유


MLflow를 사용하여 큰 언어 모델 평가

이 문서에서는 mlflow.evaluate에 패키지된 MLflow의 LLM(대규모 언어 모델) 평가 기능인 MLflow LLM Evaluate를 소개합니다. 이 문서에서는 LLM을 평가하는 데 필요한 항목과 지원되는 평가 메트릭에 대해서도 설명합니다.

MLflow LLM 평가란?

LLM 성능 평가는 비교할 단일 근거 진실이 없는 경우가 많기 때문에 기존 ML 모델과 약간 다릅니다. MLflow는 LLM을 평가하는 데 도움이 되는 API mlflow.evaluate() 를 제공합니다.

MLflow의 LLM 평가 기능은 세 가지 기본 구성 요소로 구성됩니다.

  • 평가할 모델: MLflow pyfunc 모델, 예측 열이 있는 DataFrame, 등록된 MLflow 모델을 가리키는 URI 또는 HuggingFace 텍스트 요약 파이프라인과 같이 모델을 나타내는 Python 호출 가능 모델일 수 있습니다.
  • 메트릭: 계산할 메트릭, LLM 평가는 LLM 메트릭을 사용합니다.
  • 평가 데이터: 모델이 평가되는 데이터는 Pandas DataFrame, Python 목록, numpy 배열 또는 mlflow.data.dataset.Dataset 인스턴스일 수 있습니다.

요구 사항

  • MLflow 2.8 이상.
  • LLM을 mlflow.evaluate()평가하려면 LLM이 다음 중 하나여야 합니다.
    • mlflow.pyfunc.PyFuncModel 기록된 mlflow.pyfunc.PyFuncModel 모델을 가리키는 인스턴스 또는 URI입니다.
    • 문자열 입력을 사용하고 단일 문자열을 출력하는 사용자 지정 Python 함수입니다. 호출 가능 항목은 인수 없이 params 서명과 mlflow.pyfunc.PyFuncModel.predict 일치해야 합니다. 함수는 다음을 수행해야 합니다.
      • data, Python 목록, 사전 또는 scipy 행렬일 numpy.ndarraypandas.Dataframe수 있는 유일한 인수로 사용합니다.
      • 다음 pandas.DataFramepandas.Seriesnumpy.ndarray 중 하나를 반환합니다.
    • 정적 데이터 세트입니다.

MLflow 모델을 사용하여 평가

LLM을 MLflow 모델로 평가할 수 있습니다. 모델을 인스턴스로 mlflow.pyfunc.PyFuncModel 변환하는 방법에 대한 자세한 지침은 사용자 지정 pyfunc 모델을 만드는 방법을 참조하세요.

모델을 MLflow 모델로 평가하기 위해 Databricks는 다음 단계를 수행하는 것이 좋습니다.

참고 항목

Azure OpenAI 서비스를 대상으로 하는 모델을 성공적으로 기록하려면 인증 및 기능에 대해 다음 환경 변수를 지정해야 합니다. 자세한 내용은 MLflow를 사용한 OpenAI 설명서를 참조하세요.

os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
os.environ["OPENAI_API_BASE"] = "https://<>.<>.<>.com/"
os.environ["OPENAI_DEPLOYMENT_NAME"] = "deployment-name"
  1. LLM을 MLflow 모델로 패키지하고 log_model. 각 맛(opeanai, pytorch, ...)에는 다음과 같은 mlflow.openai.log_model()자체 log_model API가 있습니다.

    with mlflow.start_run():
        system_prompt = "Answer the following question in two sentences"
        # Wrap "gpt-3.5-turbo" as an MLflow model.
        logged_model_info = mlflow.openai.log_model(
            model="gpt-3.5-turbo",
            task=openai.ChatCompletion,
            artifact_path="model",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": "{question}"},
            ],
        )
    
  2. 로깅된 모델의 URI를 다음에서 모델 인스턴스로 사용합니다.mlflow.evaluate()

    results = mlflow.evaluate(
        logged_model_info.model_uri,
        eval_data,
        targets="ground_truth",
        model_type="question-answering",
    )
    

사용자 지정 함수를 사용하여 평가

MLflow 2.8.0 이상 mlflow.evaluate() 에서는 모델을 MLflow에 기록할 필요 없이 Python 함수 평가를 지원합니다. 이 기능은 모델을 기록하지 않고 평가하려는 경우에 유용합니다. 다음 예제에서는 함수를 평가하는 데 사용합니다 mlflow.evaluate() .

또한 다음 코드를 실행하도록 OpenAI 인증을 설정해야 합니다.

eval_data = pd.DataFrame(
    {
        "inputs": [
            "What is MLflow?",
            "What is Spark?",
        ],
        "ground_truth": [
            "MLflow is an open-source platform for managing the end-to-end machine learning (ML) lifecycle. It was developed by Databricks, a company that specializes in big data and machine learning solutions. MLflow is designed to address the challenges that data scientists and machine learning engineers face when developing, training, and deploying machine learning models.",
            "Apache Spark is an open-source, distributed computing system designed for big data processing and analytics. It was developed in response to limitations of the Hadoop MapReduce computing model, offering improvements in speed and ease of use. Spark provides libraries for various tasks such as data ingestion, processing, and analysis through its components like Spark SQL for structured data, Spark Streaming for real-time data processing, and MLlib for machine learning tasks",
        ],
    }
)

def openai_qa(inputs):
    answers = []
    system_prompt = "Please answer the following question in formal language."
    for index, row in inputs.iterrows():
        completion = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": "{row}"},
            ],
        )
        answers.append(completion.choices[0].message.content)

    return answers

with mlflow.start_run() as run:
    results = mlflow.evaluate(
        openai_qa,
        eval_data,
        model_type="question-answering",
    )

정적 데이터 세트를 사용하여 평가

MLflow 2.8.0 이상의 mlflow.evaluate() 경우 모델을 지정하지 않고 정적 데이터 세트 평가를 지원합니다. 이는 모델 출력을 Pandas DataFrame 또는 MLflow PandasDataset의 열에 저장하고 모델을 다시 실행하지 않고 정적 데이터 세트를 평가하려는 경우에 유용합니다.

모델 출력을 설정하고 model=None인수에 data 넣습니다. 이 구성은 데이터가 Pandas DataFrame인 경우에만 적용됩니다.

Pandas DataFrame을 사용하는 경우 다음의 최상위 predictions 매개 변수 mlflow.evaluate()를 사용하여 모델 출력을 포함하는 열 이름을 지정해야 합니다.

import mlflow
import pandas as pd

eval_data = pd.DataFrame(
    {
        "inputs": [
            "What is MLflow?",
            "What is Spark?",
        ],
        "ground_truth": [
            "MLflow is an open-source platform for managing the end-to-end machine learning (ML) lifecycle. "
            "It was developed by Databricks, a company that specializes in big data and machine learning solutions. "
            "MLflow is designed to address the challenges that data scientists and machine learning engineers "
            "face when developing, training, and deploying machine learning models.",
            "Apache Spark is an open-source, distributed computing system designed for big data processing and "
            "analytics. It was developed in response to limitations of the Hadoop MapReduce computing model, "
            "offering improvements in speed and ease of use. Spark provides libraries for various tasks such as "
            "data ingestion, processing, and analysis through its components like Spark SQL for structured data, "
            "Spark Streaming for real-time data processing, and MLlib for machine learning tasks",
        ],
        "predictions": [
            "MLflow is an open-source platform that provides handy tools to manage Machine Learning workflow "
            "lifecycle in a simple way",
            "Spark is a popular open-source distributed computing system designed for big data processing and analytics.",
        ],
    }
)

with mlflow.start_run() as run:
    results = mlflow.evaluate(
        data=eval_data,
        targets="ground_truth",
        predictions="predictions",
        extra_metrics=[mlflow.metrics.genai.answer_similarity()],
        evaluators="default",
    )
    print(f"See aggregated evaluation results below: \n{results.metrics}")

    eval_table = results.tables["eval_results_table"]
    print(f"See evaluation table below: \n{eval_table}")

LLM 평가 메트릭 형식

MLflow에는 두 가지 유형의 LLM 평가 메트릭이 있습니다.

  • 다음과 같은 mlflow.metrics.genai.answer_relevance점수 매기기를 위해 OpenAI와 같은 SaaS 모델을 사용하는 메트릭 이러한 메트릭은 .를 사용하여 mlflow.metrics.genai.make_genai_metric()만들어집니다. 각 데이터 레코드에 대해 이러한 메트릭은 다음 정보로 구성된 하나의 프롬프트를 SaaS 모델에 보내고 모델 응답에서 점수를 추출합니다.
    • 메트릭 정의입니다.
    • 메트릭 채점 조건입니다.
    • 참조 예제입니다.
    • 입력 데이터 또는 컨텍스트입니다.
    • 모델 출력입니다.
    • [선택 사항] 지상 진실.
  • 함수 기반 행별 메트릭입니다. 이러한 메트릭은 Rouge mlflow.metrics.rougeL또는 Flesch Kincaidmlflow.metrics.flesch_kincaid_grade_level와 같은 특정 함수를 기반으로 각 데이터 레코드(Pandas 또는 Spark DataFrame의 측면에서 행)에 대한 점수를 계산합니다. 이러한 메트릭은 기존 메트릭과 유사합니다.

LLM을 평가할 메트릭 선택

모델을 평가할 메트릭을 선택할 수 있습니다. 지원되는 평가 메트릭에 대한 전체 참조는 MLflow 평가 설명서에서 찾을 수 있습니다.

구체적으로 다음과 같은 옵션을 선택할 수 있습니다.

  • 모델 유형에 대해 미리 정의된 기본 메트릭을 사용합니다.
  • 사용자 지정 메트릭 목록을 사용합니다.

미리 선택한 작업에 기본 메트릭을 사용하려면 아래 예제와 mlflow.evaluate같이 인수를 지정 model_type 합니다.

results = mlflow.evaluate(
    model,
    eval_data,
    targets="ground_truth",
    model_type="question-answering",
)

이 표에는 지원되는 LLM 모델 형식 및 관련 기본 메트릭이 요약되어 있습니다.

question-answering text-summarization text
정확한 일치 루즈 독성*
독성* 독성* ari_grade_level**
ari_grade_level** ari_grade_level** flesch_kincaid_grade_level**
flesch_kincaid_grade_level** flesch_kincaid_grade_level**

* 패키지 평가, 토치변압기가 필요합니다.

** 패키지 텍스트 통계가 필요합니다.

패키지 평가, nltk루즈 점수가 필요합니다.

사용자 지정 메트릭 목록 사용

인수에서 메트릭 extra_metrics 의 사용자 지정 목록을 지정할 수 있습니다 mlflow.evaluate.

미리 정의된 모델 형식의 기본 메트릭 목록에 메트릭을 추가하려면 매개 변수를 model_type 유지하고 메트릭을 extra_metrics추가합니다. 다음은 모델에 대한 question-answering 모든 메트릭을 사용하여 모델을 mlflow.metrics.latency()평가하고.

results = mlflow.evaluate(
    model,
    eval_data,
    targets="ground_truth",
    model_type="question-answering",
    extra_metrics=[mlflow.metrics.latency()],
)

기본 메트릭 계산을 사용하지 않도록 설정하고 선택한 메트릭만 계산하려면 인수를 model_type 제거하고 원하는 메트릭을 정의합니다.

results = mlflow.evaluate(model,
                          eval_data,
                          targets="ground_truth",
                          extra_metrics=[mlflow.metrics.toxicity(), mlflow.metrics.latency()],
                        )

LLM을 판사로 사용하는 메트릭

또한 LLM을 판사 extra_metrics 로 사용하는 미리 통조림 메트릭을 인수에 추가할 수도 있습니다 mlflow.evaluate(). 이러한 LLM을 판사 메트릭으로 나열하려면 LLM을 판사로 사용하는 메트릭을 참조하세요.

참고 항목

또한 사용자 지정 LLM을 판사 및 추론 기반 평가 메트릭으로 만들 수 있습니다.

from  mlflow.metrics.genai import answer_relevance

answer_relevance_metric = answer_relevance(model="openai:/gpt-4")

eval_df = pd.DataFrame() # Index(['inputs', 'predictions', 'context'], dtype='object')

eval_results = mlflow.evaluate(
    data = eval_df, # evaluation data
    model_type="question-answering",
    predictions="predictions", # prediction column_name from eval_df
    extra_metrics=[answer_relevance_metric]
)

평가 결과 보기

mlflow.evaluate() 는 평가 결과를 인스턴스로 반환합니다 mlflow.models.EvaluationResult .

선택한 메트릭의 점수를 보려면 평가 결과의 다음 특성을 검사 수 있습니다.

  • metrics: 평가 데이터 세트의 평균 또는 분산과 같은 집계된 결과를 저장합니다. 다음은 위의 코드 예제에서 두 번째 패스를 받아 집계된 결과를 인쇄하는 데 중점을 둡니다.

    with mlflow.start_run() as run:
        results = mlflow.evaluate(
            data=eval_data,
            targets="ground_truth",
            predictions="predictions",
            extra_metrics=[mlflow.metrics.genai.answer_similarity()],
            evaluators="default",
        )
        print(f"See aggregated evaluation results below: \n{results.metrics}")
    
  • tables['eval_results_table']: 행별 평가 결과를 저장합니다.

    with mlflow.start_run() as run:
        results = mlflow.evaluate(
            data=eval_data,
            targets="ground_truth",
            predictions="predictions",
            extra_metrics=[mlflow.metrics.genai.answer_similarity()],
            evaluators="default",
        )
        print(
            f"See per-data evaluation results below: \n{results.tables['eval_results_table']}"
        )
    

MLflow 예제 Notebook을 사용하여 LLM 평가

MLflow 예제 Notebook을 사용한 다음 LLM 평가는 사용 사례 지향 예제입니다.

MLflow 예제 Notebook을 사용하여 LLM 평가

전자 필기장 가져오기