본문 바로가기
WIKI 기술 지식 베이스

ML inference processor

원문 보기 위키 갱신

출처: 문서

본문

ML inference 프로세서

ml_inference 프로세서는 OpenSearch ML Commons 플러그인에 등록된 머신러닝(ML) 모델을 호출하는 데 사용해요. 모델 출력은 수집된 문서에 새 필드로 추가돼요.

사전 조건
ml_inference 프로세서를 사용하기 전에, OpenSearch 클러스터에서 호스팅되는 로컬 ML 모델이 있거나 ML Commons 플러그인을 통해 OpenSearch 클러스터에 연결된 외부 호스팅 모델이 있어야 해요. 로컬 모델에 대한 자세한 내용은 OpenSearch 내에서 ML 모델 사용하기를, 외부 호스팅 모델에 대한 자세한 내용은 외부 호스팅 모델 연결하기를 참고하세요. {: .note}

문법

다음은 ml-inference 프로세서의 문법이에요:

{
  "ml_inference": {
    "model_id": "<model_id>",
    "function_name": "<function_name>",
    "full_response_path": "<full_response_path>",
    "model_config":{
      "<model_config_field>": "<config_value>"
    },
    "model_input": "<model_input>",
    "input_map": [
      {
        "<model_input_field>": "<document_field>"
      }
    ],
    "output_map": [
      {
        "<new_document_field>": "<model_output_field>"
      }
    ],
    "override": "<override>"
  }
}

{% include copy.html %}

설정 파라미터

다음 표는 ml-inference 프로세서의 필수 및 선택 파라미터를 정리한 거예요.

파라미터 데이터 타입 필수/선택 설명
model_id String 필수 프로세서가 사용하는 ML 모델의 ID예요.
function_name String 외부 호스팅 모델은 선택

로컬 모델은 필수
프로세서에 설정된 ML 모델의 함수 이름이에요. 로컬 모델의 유효한 값은 sparse_encoding, sparse_tokenize, text_embedding, text_similarity예요. 외부 호스팅 모델의 유효한 값은 remote예요. 기본값은 remote예요.
model_config Object 선택 ML 모델의 커스텀 설정 옵션이에요. 외부 호스팅 모델의 경우, 이 값을 설정하면 기본 커넥터 파라미터가 재정의돼요. 로컬 모델의 경우, model_config를 model_input에 추가해서 등록 시 설정한 모델 구성을 재정의할 수 있어요. 자세한 내용은 model_config 객체를 참고하세요.
model_input String 외부 호스팅 모델은 선택

로컬 모델은 필수
모델이 기대하는 입력 필드 형식을 정의하는 템플릿이에요. 로컬 모델 타입마다 사용하는 입력 세트가 다를 수 있어요. 외부 호스팅 모델의 기본값은 "{ \"parameters\": ${ml_inference.parameters} }예요.
input_map Array 외부 호스팅 모델은 선택

로컬 모델은 필수
수집된 문서 필드를 모델 입력 필드에 매핑하는 방법을 지정하는 배열이에요. 배열의 각 요소는 "<model_input_field>": "<document_field>" 형식의 맵이고, 문서 필드 하나에 대한 모델 호출 한 번에 해당해요. 외부 호스팅 모델에 입력 매핑을 지정하지 않으면, 문서의 모든 필드가 입력으로 모델에 직접 전달돼요. input_map 크기는 모델이 호출되는 횟수(Predict API 요청 수)를 나타내요.
<model_input_field> String 외부 호스팅 모델은 선택

로컬 모델은 필수
모델 입력 필드 이름이에요.
<document_field> String 외부 호스팅 모델은 선택

로컬 모델은 필수
모델 입력으로 사용되는 수집 문서 필드의 이름 또는 JSON 경로예요.
output_map Array 외부 호스팅 모델은 선택

로컬 모델은 필수
모델 출력 필드를 수집 문서의 새 필드에 매핑하는 방법을 지정하는 배열이에요. 배열의 각 요소는 "<new_document_field>": "<model_output_field>" 형식의 맵이에요.
<new_document_field> String 외부 호스팅 모델은 선택

로컬 모델은 필수
모델 출력(model_output에 지정됨)이 저장되는 수집 문서의 새 필드 이름이에요. 외부 호스팅 모델에 출력 매핑을 지정하지 않으면, 모델 출력의 모든 필드가 새 문서 필드에 추가돼요.
<model_output_field> String 외부 호스팅 모델은 선택

로컬 모델은 필수
new_document_field에 저장될 모델 출력 내 필드의 이름 또는 JSON 경로예요.
full_response_path Boolean 선택 model_output_field에 필드 이름 대신 필드까지의 전체 JSON 경로가 담겨 있다면 이 파라미터를 true로 설정하세요. 그러면 필드 값을 얻기 위해 모델 출력이 전체 파싱돼요. 로컬 모델의 기본값은 true이고 외부 호스팅 모델의 기본값은 false예요.
ignore_missing Boolean 선택 true이고 input_map 또는 output_map에 정의된 입력 필드 중 하나라도 누락되면, 누락된 필드는 무시돼요. 그렇지 않으면 누락된 필드가 실패를 유발해요. 기본값은 false예요.
ignore_failure Boolean 선택 오류가 발생해도 프로세서가 실행을 계속할지 여부를 지정해요. true이면 실패가 무시되고 수집이 계속돼요. false이면 실패가 발생할 경우 수집이 취소돼요. 기본값은 false예요.
override Boolean 선택 수집된 문서에 이미 <new_document_field>에 지정된 이름의 필드가 있을 때 관련이 있어요. override가 false이면 입력 필드는 건너뛰어져요. true이면 기존 필드 값이 새 모델 출력으로 덮어 쓰여져요. 기본값은 false예요.
max_prediction_tasks Integer 선택 문서 수집 중에 실행될 수 있는 동시 모델 호출의 최대 개수예요. 기본값은 10이에요.
description String 선택 프로세서에 대한 간단한 설명이에요.
tag String 선택 프로세서의 식별자 태그예요. 같은 타입의 프로세서들을 구분하는 디버깅에 유용해요.

input_map과 output_map 매핑은 복잡한 데이터 구조를 지정하기 위한 표준 JSON path 표기법을 지원해요. {: .note}

프로세서 사용하기

다음 단계를 따라 파이프라인에서 프로세서를 사용하세요. 프로세서를 생성할 때는 모델 ID를 제공해야 해요. 파이프라인을 테스트하거나 프로세서로 문서를 수집하기 전에, 모델이 성공적으로 배포되었는지 확인하세요. Get Model API를 사용해서 모델 상태를 확인할 수 있어요.

로컬 모델의 경우, 모델 입력 형식을 지정하는 model_input 필드를 반드시 제공해야 해요. model_config에 입력 필드가 있다면 model_input에 추가하세요.

원격 모델의 경우, model_input 필드는 선택 사항이고 기본값은 "{ \"parameters\": ${ml_inference.parameters} }이에요.

예시: 외부 호스팅 모델

다음 예시는 외부 호스팅 모델로 ml_inference 프로세서를 설정하는 방법이에요.

1단계: 파이프라인 생성하기

다음 예시는 외부 호스팅 텍스트 임베딩 모델을 위한 수집 파이프라인을 생성해요. 이 모델은 input 필드가 필요하고 data 필드에 결과를 생성해요. passage_text 필드의 텍스트를 텍스트 임베딩으로 변환하고 임베딩을 passage_embedding 필드에 저장해요. 프로세서 설정에서 function_name이 명시적으로 지정되지 않았으므로, 기본값인 remote가 적용되어 외부 호스팅 모델을 나타내요:

PUT /_ingest/pipeline/ml_inference_pipeline
{
  "description": "Generate passage_embedding for ingested documents",
  "processors": [
    {
      "ml_inference": {
        "model_id": "<your model id>",
        "input_map": [
          {
            "input": "passage_text"
          }
        ],
        "output_map": [
          {
            "passage_embedding": "data"
          }
        ]
      }
    }
  ]
}

{% include copy-curl.html %}

외부 호스팅 모델에 대한 Predict API 요청에서는, 보통 모든 필드가 parameters 객체 안에 중첩돼요:

POST /_plugins/_ml/models/cleMb4kBJ1eYAeTMFFg4/_predict
{
  "parameters": {
    "input": [
      {
        ...
      }
    ]
  }
}

외부 호스팅 모델의 input_map을 지정할 때는, 도트 경로인 parameters.input을 제공하는 대신 input 필드를 직접 참조할 수 있어요:

"input_map": [
  {
    "input": "passage_text"
  }
]

2단계(선택): 파이프라인 테스트하기

문서를 수집하기 전에 파이프라인을 테스트하는 것이 좋아요. {: .tip}

파이프라인을 테스트하려면 다음 쿼리를 실행하세요:

POST _ingest/pipeline/ml_inference_pipeline/_simulate
{
  "docs": [
    {
      "_index": "testindex1",
      "_id": "1",
      "_source":{
         "passage_text": "hello world"
      }
    }
  ]
}

{% include copy-curl.html %}

응답

응답은 프로세서가 passage_embedding 필드에 텍스트 임베딩을 생성했음을 확인해 줘요. 이제 문서에는 passage_text와 passage_embedding 필드가 모두 들어 있어요:

{
  "docs" : [
    {
      "doc" : {
        "_index" : "testindex1",
        "_id" : "1",
        "_source" : {
          "passage_embedding" : [
            0.017304314,
            -0.021530833,
            0.050184276,
            0.08962978,
            ...
          ],
          "passage_text" : "hello world"
        },
        "_ingest" : {
          "timestamp" : "2023-10-11T22:35:53.654650086Z"
        }
      }
    }
  ]
}

수집 파이프라인을 만든 후에는, 수집을 위한 인덱스를 생성하고 인덱스에 문서를 수집해야 해요. {: .note}

예시: 로컬 모델

다음 예시는 로컬 모델로 ml_inference 프로세서를 설정하는 방법이에요.

1단계: 파이프라인 생성하기

다음 예시는 huggingface/sentence-transformers/all-distilroberta-v1 로컬 모델을 위한 수집 파이프라인을 생성해요. 이 모델은 OpenSearch 클러스터에서 호스팅되는 sentence transformer 사전 학습 모델이에요.

Predict API로 모델을 호출하면, 요청은 다음과 같아요:

POST /_plugins/_ml/_predict/text_embedding/cleMb4kBJ1eYAeTMFFg4
{
  "text_docs":[ "today is sunny"],
  "return_number": true,
  "target_response": ["sentence_embedding"]
}

이 스키마를 사용해서 model_input을 다음과 같이 지정하세요:

 "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }"

input_map에서 book.*.chunk.text.*.context 문서 필드를 모델이 기대하는 text_docs 필드에 매핑하세요:

"input_map": [
  {
    "text_docs": "book.*.chunk.text.*.context"
  }
]

임베딩으로 변환할 필드를 JSON 경로로 지정했기 때문에, 입력 필드를 얻기 위해 전체 JSON 문서가 파싱되도록 full_response_path를 true로 설정해야 해요:

"full_response_path": true

인덱싱하는 문서는 다음과 같이 나타나요. context 필드의 텍스트가 임베딩 생성에 사용돼요:

"book": [
  {
    "chunk": {
      "text": [
        {
          "chapter": "first chapter",
          "context": "this is the first part"
        }
      ]
    }
  }
]

Predict API 요청은 다음 응답을 반환해요:

{
  "inference_results" : [
    {
      "output" : [
        {
          "name" : "sentence_embedding",
          "data_type" : "FLOAT32",
          "shape" : [
            768
          ],
          "data" : [
            0.25517133,
            -0.28009856,
            0.48519906,
            ...
          ]
        }
      ]
    }
  ]
}

모델은 $.inference_results.*.output.*.data 필드에 임베딩을 생성해요. output_map은 이 필드를 수집된 문서의 새로 생성된 book.*.chunk.text.*.context_embedding 필드에 매핑해요:

"output_map": [
  {
    "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data"
  }
]

로컬 모델로 ml_inference 프로세서를 설정하려면 function_name을 명시적으로 지정해야 해요. 이 예시에서 function_name은 text_embedding이에요. 유효한 function_name 값에 대한 정보는 설정 파라미터를 참고하세요.

이 예시에서 로컬 모델을 사용하는 ml_inference 프로세서의 최종 설정은 다음과 같아요:

PUT /_ingest/pipeline/ml_inference_pipeline_local
{
  "description": "ingests reviews and generates embeddings",
  "processors": [
    {
      "ml_inference": {
        "function_name": "text_embedding",
        "full_response_path": true,
        "model_id": "<your model id>",
        "model_config": {
          "return_number": true,
          "target_response": ["sentence_embedding"]
        },
        "model_input": "{ \"text_docs\": ${input_map.text_docs}, \"return_number\": ${model_config.return_number}, \"target_response\": ${model_config.target_response} }",
        "input_map": [
          {
            "text_docs": "book.*.chunk.text.*.context"
          }
        ],
        "output_map": [
          {
            "book.*.chunk.text.*.context_embedding": "$.inference_results.*.output.*.data"
          }
        ],
        "ignore_missing": true,
        "ignore_failure": true
      }
    }
  ]
}

{% include copy-curl.html %}

2단계(선택): 파이프라인 테스트하기

파이프라인을 테스트하려면 다음 쿼리를 실행하세요:

POST _ingest/pipeline/ml_inference_pipeline/_simulate
{
  "docs": [
    {
      "_index": "my_books",
      "_id": "1",
      "_source": {
        "book": [
          {
            "chunk": {
              "text": [
                {
                  "chapter": "first chapter",
                  "context": "this is the first part"
                },
                {
                  "chapter": "first chapter",
                  "context": "this is the second part"
                }
              ]
            }
          },
          {
            "chunk": {
              "text": [
                {
                  "chapter": "second chapter",
                  "context": "this is the third part"
                },
                {
                  "chapter": "second chapter",
                  "context": "this is the fourth part"
                }
              ]
            }
          }
        ]
      }
    }
  ]
}

{% include copy-curl.html %}

응답

응답은 프로세서가 context_embedding 필드에 텍스트 임베딩을 생성했음을 확인해 줘요. 이제 문서에는 같은 경로에 context와 context_embedding 필드가 모두 들어 있어요:

{
  "docs" : [
    {
      "doc" : {
        "_index": "my_books",
        "_id": "1",
        "_source": {
          "book": [
            {
              "chunk": {
                "text": [
                  {
                    "chapter": "first chapter",
                    "context": "this is the first part",
                    "context_embedding": [
                      0.15756914,
                      0.05150984,
                      0.25225413,
                      0.4941875,
                      ...
                    ]
                  },
                  {
                    "chapter": "first chapter",
                    "context": "this is the second part",
                    "context_embedding": [
                      0.10526893,
                      0.026559234,
                      0.28763372,
                      0.4653795,
                      ...
                    ]
                  }
                ]
              }
            },
            {
              "chunk": {
                "text": [
                  {
                    "chapter": "second chapter",
                    "context": "this is the third part",
                    "context_embedding": [
                      0.017304314,
                      -0.021530833,
                      0.050184276,
                      0.08962978,
                      ...
                    ]
                  },
                  {
                    "chapter": "second chapter",
                    "context": "this is the fourth part",
                    "context_embedding": [
                      0.37742054,
                      0.046911318,
                      1.2053889,
                      0.04663613,
                      ...
                    ]
                  }
                ]
              }
            }
          ]
        }
      }
    }
  ]
}

수집 파이프라인을 만든 후에는, 수집을 위한 인덱스를 생성하고 인덱스에 문서를 수집해야 해요. {: .note}

더 알아보기 (Learn more)