Hugging Face 파이프라인

Snowflake Model Registry는 `transformers.Pipeline<https://huggingface.co/docs/transformers/main_classes/pipelines#transformers.pipeline>`_ 메서드를 사용하여 로드할 수 있는 `변환기 <https://huggingface.co/docs/transformers/index>`_로 정의된 모든 Hugging Face 모델을 지원합니다.

다음 방법 중 하나를 사용하여 Hugging Face 모델을 Model Registry에 기록합니다.

  1. Snowsight 를 사용하여 Hugging Face에서 모델을 가져와 배포합니다. 지침은 외부 서비스에서 모델 가져오기 및 배포 섹션을 참조하세요.

  2. snowflake.ml.model.models.huggingface.TransformersPipeline 인스턴스를 생성하고 log_model():을 호출합니다.

    # reg: snowflake.ml.registry.Registry
    
    from snowflake.ml.model.models import huggingface
    
    
    model = huggingface.TransformersPipeline(
        task="text-classification",
        model="ProsusAI/finbert",
        # compute_pool_for_log=... # Optional
    )
    
    mv = reg.log_model(model, model_name='finbert', version_name='v5')
    
    Copy

    중요

    • compute_pool_for_log 인자를 지정하지 않은 경우 모델은 기본 CPU 컴퓨팅 풀을 사용하여 로깅됩니다.

    • compute_pool_for_log 인자를 지정한 경우 모델은 지정된 컴퓨팅 풀을 사용하여 로깅됩니다.

    • compute_pool_for_log 인자를 None으로 설정하면 모델 파일이 로컬에 다운로드된 다음 모델 레지스트리에 업로드됩니다. 이를 위해서는 `huggingface-hub <https://pypi.org/project/huggingface-hub/>`_가 설치되어 있어야 합니다.

  3. 메모리의 Hugging Face에서 모델 로드 및 Model Registry에 기록합니다.

    # reg: snowflake.ml.registry.Registry
    
    lm_hf_model = transformers.pipeline(
        task="text-generation",
        model="bigscience/bloom-560m",
        token="...",  # Put your HuggingFace token here.
        return_full_text=False,
        max_new_tokens=100,
    )
    
    lmv = reg.log_model(lm_hf_model, model_name='bloom', version_name='v560m')
    
    Copy

Snowflake Notebooks를 사용하는 경우 모델의 가중치를 다운로드하려면 노트북에 외부 액세스 통합이 연결되어 있어야 합니다. 이 통합은 다음 호스트로의 송신을 허용하는 데 필요합니다.

  • huggingface.co

  • hub-ci.huggingface.co

  • cdn-lfs-us-1.hf.co

  • cdn-lfs-eu-1.hf.co

  • cdn-lfs.hf.co

  • transfer.xethub.hf.co

  • cas-server.xethub.hf.co

  • cas-bridge.xethub.hf.c

참고

이 호스트 목록은 Hugging Face에 액세스하는 데 필요한 호스트 목록이며 언제든지 변경될 수 있습니다. 모델에는 다른 소스의 아티팩트가 필요할 수 있으며, 이 아티팩트는 송신이 허용되는 네트워크 규칙에 추가되어야 합니다.

다음 예제에서는 노트북과 함께 사용하기 위한 새 외부 액세스 통합 ``huggingface_network_rule``을 생성합니다.

CREATE NETWORK RULE huggingface_network_rule
TYPE = HOST_PORT
VALUE_LIST = (
    'huggingface.co',
    'hub-ci.huggingface.co',
    'cdn-lfs-us-1.hf.co',
    'cdn-lfs-eu-1.hf.co',
    'cdn-lfs.hf.co',
    'transfer.xethub.hf.co',
    'cas-server.xethub.hf.co',
    'cas-bridge.xethub.hf.co'
)
MODE = EGRESS
COMMENT = 'Network Rule for Hugging Face external access';

CREATE EXTERNAL ACCESS INTEGRATION huggingface_access_integration
ALLOWED_NETWORK_RULES = (huggingface_network_rule)
ENABLED = true;
Copy

자세한 내용은 외부 액세스 통합 생성 및 사용하기 섹션을 참조하십시오.

외부 액세스 통합이 생성되면 이를 노트북에 연결하고 Hugging Face 모델 리포지토리에 액세스하여 모델의 가중치와 구성을 다운로드합니다. 자세한 내용은 Snowflake Notebooks 에 대한 외부 액세스 설정 섹션을 참조하십시오.

모델 레지스트리 API

log_model`을 호출하는 경우 ``options`() 사전은 다음 키를 지원합니다.

옵션 키

설명

타입

target_methods

모델 오브젝트에서 사용할 수 있는 메서드 목록입니다. Hugging Face 모델은 기본적으로 오브젝트의 __call__ 메서드를 사용합니다(있는 경우).

list[str]

cuda_version

GPU가 있는 플랫폼에 배포할 때 사용되는 CUDA 런타임 버전입니다. ``None``으로 설정하면 GPU가 있는 플랫폼에 모델을 배포할 수 없습니다. 기본값은 ``12.4``입니다.

Optional[str]

모델 레지스트리는 파이프라인에 다음 목록의 작업이 하나 포함되어 있는 경우에만 signatures 인자를 추론합니다.

참고

작업 이름은 대소문자를 구분합니다.

log_model``에 대한 ``sample_input_data 인자는 Hugging Face 모델에서 무시됩니다. 레지스트리가 대상 메서드의 서명을 알 수 있도록 위 목록에 없는 Hugging Face 모델을 로깅할 때 signatures 인자를 지정합니다.

추론된 서명을 보려면 show_functions() 메서드를 호출합니다. 이 서명은 모델 함수 입력에 필요한 유형 및 열 이름과 출력 형식을 제공합니다. 다음 예제에서는 text-generation 작업이 있는 모델 ``bigscience/bloom-560m``의 서명을 보여줍니다.

{'name': '__CALL__',
  'target_method': '__call__',
  'signature': ModelSignature(
                      inputs=[
                          FeatureSpec(dtype=DataType.STRING, name='inputs')
                      ],
                      outputs=[
                          FeatureSpec(dtype=DataType.STRING, name='outputs')
                      ]
                  )}]

다음 예제에서는 이전 서명을 사용하여 모델을 호출하는 방법을 보여줍니다.

# model: snowflake.ml.model.ModelVersion

import pandas as pd

remote_prediction = model.run(pd.DataFrame(["Hello, how are you?"], columns=["inputs"]))
Copy

사용법 노트

  • 많은 Hugging Face 모델은 크기가 커서 표준 웨어하우스에 맞지 않습니다. Snowpark에 최적화된 웨어하우스를 사용하거나 더 작은 버전의 모델을 선택하세요. 예를 들어 Llama-2-70b-chat-hf 모델을 사용하는 대신 Llama-2-7b-chat-hf 모델을 사용합니다.

  • Snowflake 웨어하우스에는 GPU가 없습니다. CPU에 최적화된 Hugging Face 모델만 사용하십시오.

  • 일부 Hugging Face 변환기는 입력 행마다 사전 배열을 반환합니다. 모델 레지스트리는 사전 배열을 JSON 배열 표현이 포함된 문자열로 변환합니다. 예를 들어 다중 출력 질문 답변 출력은 이와 비슷하게 보입니다.

    '[{"score": 0.61094731092453, "start": 139, "end": 178, "answer": "learn more about the world of athletics"},
    {"score": 0.17750297486782074, "start": 139, "end": 180, "answer": "learn more about the world of athletics.\""}]'
    

# Prepare model

import transformers
import pandas as pd

finbert_model = transformers.pipeline(
    task="text-classification",
    model="ProsusAI/finbert",
    top_k=2,
)

# Log the model
mv = registry.log_model(
    finbert_model,
    model_name="finbert",
    version_name="v1",
)

# Use the model
mv.run(pd.DataFrame(
        [
            ["I have a problem with my Snowflake that needs to be resolved asap!!", ""],
            ["I would like to have udon for today's dinner.", ""],
        ]
    )
)
Copy

결과:

0  [{"label": "negative", "score": 0.8106237053871155}, {"label": "neutral", "score": 0.16587384045124054}]
1  [{"label": "neutral", "score": 0.9263970851898193}, {"label": "positive", "score": 0.05286872014403343}]

Hugging Face 파이프라인에 대한 추론된 서명

이 섹션에서는 필요한 입력 및 예상 출력에 대한 설명과 예제를 포함하여 지원되는 Hugging Face 파이프라인의 추론된 서명에 대해 설명합니다. 모든 입력과 출력은 Snowpark DataFrames입니다.

마스크 채우기 파이프라인

작업이 “마스크 채우기 “ 인 파이프라인으로, 입력과 출력은 다음과 같습니다.

입력

  • inputs: 채워야 할 마스크가 있는 문자열입니다.

예:

--------------------------------------------------
|"inputs"                                        |
--------------------------------------------------
|LynYuu is the [MASK] of the Grand Duchy of Yu.  |
--------------------------------------------------

출력

  • outputs: 오브젝트 목록의 JSON 표현이 포함된 문자열로, 각 키에는 score, token, token_str 또는 sequence 같은 키가 포함될 수 있습니다. 자세한 내용은 FillMaskPipeline 섹션을 참조하십시오.

예:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"outputs"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|[{"score": 0.9066258072853088, "token": 3007, "token_str": "capital", "sequence": "lynyuu is the capital of the grand duchy of yu."}, {"score": 0.08162177354097366, "token": 2835, "token_str": "seat", "sequence": "lynyuu is the seat of the grand duchy of yu."}, {"score": 0.0012052370002493262, "token": 4075, "token_str": "headquarters", "sequence": "lynyuu is the headquarters of the grand duchy of yu."}, {"score": 0.0006560495239682496, "token": 2171, "token_str": "name", "sequence": "lynyuu is the name of the grand duchy of yu."}, {"score": 0.0005427763098850846, "token": 3200, "token_str"...  |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="fill-mask",
    model="google-bert/bert-base-uncased",
)

mv = registry.log_model(
    model=model,
    model_name="GOOGLE_BERT_BASE_UNCASED",
)

input_df = pd.DataFrame([{"text": "LynYuu is the [MASK] of the Grand Duchy of Yu."}])
mv.run(
    input_df,
    # function_name="__call__", # Optional
)
Copy

토큰 분류

작업이 “ner” 또는 “토큰 분류”인 파이프라인으로, 입력과 출력은 다음과 같습니다.

입력

  • inputs: 분류할 토큰이 포함된 문자열입니다.

예:

------------------------------------------------
|"inputs"                                      |
------------------------------------------------
|My name is Izumi and I live in Tokyo, Japan.  |
------------------------------------------------

출력

  • outputs: 결과 오브젝트 목록의 JSON 표현이 포함된 문자열로, 각 키에는 entity, score, index, word, name, start 또는 end 같은 키가 포함될 수 있습니다. 자세한 내용은 TokenClassificationPipeline 섹션을 참조하십시오.

예:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"outputs"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|[{"entity": "PRON", "score": 0.9994392991065979, "index": 1, "word": "my", "start": 0, "end": 2}, {"entity": "NOUN", "score": 0.9968984127044678, "index": 2, "word": "name", "start": 3, "end": 7}, {"entity": "AUX", "score": 0.9937735199928284, "index": 3, "word": "is", "start": 8, "end": 10}, {"entity": "PROPN", "score": 0.9928083419799805, "index": 4, "word": "i", "start": 11, "end": 12}, {"entity": "PROPN", "score": 0.997334361076355, "index": 5, "word": "##zumi", "start": 12, "end": 16}, {"entity": "CCONJ", "score": 0.999173104763031, "index": 6, "word": "and", "start": 17, "end": 20}, {...  |

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="token-classification",
    model="dslim/bert-base-NER",
)

mv = registry.log_model(
    model=model,
    model_name="BERT_BASE_NER",
)

mv.run(
    pd.DataFrame([{"inputs": "My name is Izumi and I live in Tokyo, Japan."}]),
    # function_name="__call__", # Optional
)
Copy

쿼리 응답(단일 출력)

작업이 “question-answering “인 파이프라인으로, 여기서 top_k 는 설정 취소되거나 1로 설정되고, 입력과 출력은 다음과 같습니다.

입력

  • question: 답변할 질문이 포함된 문자열입니다.

  • context: 답변을 포함할 수 있는 문자열입니다.

예:

-----------------------------------------------------------------------------------
|"question"                  |"context"                                           |
-----------------------------------------------------------------------------------
|What did Doris want to do?  |Doris is a cheerful mermaid from the ocean dept...  |
-----------------------------------------------------------------------------------

출력

  • score: 0.0~1.0 사이의 부동소수점 신뢰도 점수입니다.

  • start: 컨텍스트에서 답변의 첫 번째 토큰의 정수 인덱스입니다.

  • end: 원래 컨텍스트에서 답변의 마지막 토큰의 정수 인덱스입니다.

  • answer: 찾은 답변이 포함된 문자열입니다.

예:

--------------------------------------------------------------------------------
|"score"           |"start"  |"end"  |"answer"                                 |
--------------------------------------------------------------------------------
|0.61094731092453  |139      |178    |learn more about the world of athletics  |
--------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd


model = transformers.pipeline(
    task="question-answering",
    model="deepset/roberta-base-squad2",
)

QA_input = {
    "question": "Why is model conversion important?",
    "context": "The option to convert models between FARM and transformers gives freedom to the user and let people easily switch between frameworks.",
}

mv = registry.log_model(
    model=model,
    model_name="ROBERTA_BASE_SQUAD2",
)

mv.run(
    pd.DataFrame.from_records([QA_input]),
    # function_name="__call__", # Optional
)
Copy

쿼리 응답(다중 출력)

작업이 “question-answering “인 파이프라인으로, 여기서 top_k 는 설정되고 1보다 큰 값이며, 입력과 출력은 다음과 같습니다.

입력

  • question: 답변할 질문이 포함된 문자열입니다.

  • context: 답변을 포함할 수 있는 문자열입니다.

예:

-----------------------------------------------------------------------------------
|"question"                  |"context"                                           |
-----------------------------------------------------------------------------------
|What did Doris want to do?  |Doris is a cheerful mermaid from the ocean dept...  |
-----------------------------------------------------------------------------------

출력

  • outputs: 결과 오브젝트 목록의 JSON 표현이 포함된 문자열로, 각 키에는 score, start, end 또는 answer 같은 키가 포함될 수 있습니다.

예:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"outputs"                                                                                                                                                                                                                                                                                                                                        |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|[{"score": 0.61094731092453, "start": 139, "end": 178, "answer": "learn more about the world of athletics"}, {"score": 0.17750297486782074, "start": 139, "end": 180, "answer": "learn more about the world of athletics.\""}, {"score": 0.06438097357749939, "start": 138, "end": 178, "answer": "\"learn more about the world of athletics"}]  |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd


model = transformers.pipeline(
    task="question-answering",
    model="deepset/roberta-base-squad2",
    top_k=3,
)

QA_input = {
    "question": "Why is model conversion important?",
    "context": "The option to convert models between FARM and transformers gives freedom to the user and let people easily switch between frameworks.",
}

mv = registry.log_model(
    model=model,
    model_name="ROBERTA_BASE_SQUAD2",
)

mv.run(
    pd.DataFrame.from_records([QA_input]),
    # function_name="__call__", # Optional
)
Copy

요약

작업이 “요약 “ 인 파이프라인으로, 여기서 return_tensors 는 False 또는 설정 취소되며, 입력과 출력은 다음과 같습니다.

입력

  • documents: 요약할 텍스트가 포함된 문자열입니다.

예:

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"documents"                                                                                                                                                                                               |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|Neuro-sama is a chatbot styled after a female VTuber that hosts live streams on the Twitch channel "vedal987". Her speech and personality are generated by an artificial intelligence (AI) system  wh...  |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

출력

  • summary_text: 생성된 요약이 포함된 문자열 또는 num_return_sequences 가 1보다 큰 경우 결과 목록의 JSON 표현식이 포함된 문자열이며, 각 문자열은 summary_text 를 포함한 필드가 포함된 사전입니다.

예:

---------------------------------------------------------------------------------
|"summary_text"                                                                 |
---------------------------------------------------------------------------------
| Neuro-sama is a chatbot styled after a female VTuber that hosts live streams  |
---------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd


model = transformers.pipeline(
    task="summarization",
    model="facebook/bart-large-cnn",
)

text = "The transformers library is a great library for natural language processing which provides a unified interface for many different models and tasks."

mv = registry.log_model(
    model=model,
    model_name="BART_LARGE_CNN",
)

mv.run(
    pd.DataFrame.from_records([{"documents": text}]),
    # function_name="__call__", # Optional
)
Copy

테이블 질문 답변

작업이 table-question-answering 인 파이프라인으로, 입력과 출력은 다음과 같습니다.

입력

  • query: 답변할 질문이 포함된 문자열입니다.

  • table: 답변을 포함할 수 있는 테이블을 나타내는 {column -> [values]} 형식의 JSON 직렬화 사전이 포함된 문자열입니다.

예:

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"query"                                  |"table"                                                                                                                                                                                                                                                   |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|Which channel has the most subscribers?  |{"Channel": ["A.I.Channel", "Kaguya Luna", "Mirai Akari", "Siro"], "Subscribers": ["3,020,000", "872,000", "694,000", "660,000"], "Videos": ["1,200", "113", "639", "1,300"], "Created At": ["Jun 30 2016", "Dec 4 2017", "Feb 28 2014", "Jun 23 2017"]}  |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

출력

  • answer: 가능한 답변이 포함된 문자열입니다.

  • coordinates: 답변이 이 위치한 셀의 좌표를 나타내는 정수 목록입니다.

  • cells: 답변이 위치한 셀의 내용이 포함된 문자열 목록입니다.

  • aggregator: 사용된 집계 장치의 이름이 포함된 문자열입니다.

예:

----------------------------------------------------------------
|"answer"     |"coordinates"  |"cells"          |"aggregator"  |
----------------------------------------------------------------
|A.I.Channel  |[              |[                |NONE          |
|             |  [            |  "A.I.Channel"  |              |
|             |    0,         |]                |              |
|             |    0          |                 |              |
|             |  ]            |                 |              |
|             |]              |                 |              |
----------------------------------------------------------------

코드 예제

import transformers
import pandas as pd
import json

model = transformers.pipeline(
    task="table-question-answering",
    model="microsoft/tapex-base-finetuned-wikisql",
)

data = {
    "year": [1896, 1900, 1904, 2004, 2008, 2012],
    "city": ["athens", "paris", "st. louis", "athens", "beijing", "london"],
}
query = "What is the city of the year 2004?"


mv = registry.log_model(
    model=model,
    model_name="TAPEX_BASE_FINETUNED_WIKISQL",
)

mv.run(
    pd.DataFrame.from_records([{"query": query, "table": json.dumps(data)}]),
    # function_name="__call__", # Optional
)
Copy

텍스트 분류(단일 출력)

작업이 “text-clasification “ 또는 “sentiment-analysis”인 파이프라인으로, 여기서 top_k 는 설정되지 않거나 None이며, 입력과 출력은 다음과 같습니다.

입력

  • text: 분류할 문자열입니다.

  • text_pair: text 로 분류되는 문자열로, 텍스트 유사도를 계산하는 모델과 함께 사용됩니다. 모델에서 사용하지 않으면 비워둡니다.

예:

----------------------------------
|"text"       |"text_pair"       |
----------------------------------
|I like you.  |I love you, too.  |
----------------------------------

출력

  • label: 텍스트의 분류 레이블을 나타내는 문자열입니다.

  • score: 0.0~1.0 사이의 부동소수점 신뢰도 점수입니다.

예:

--------------------------------
|"label"  |"score"             |
--------------------------------
|LABEL_0  |0.9760091304779053  |
--------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="text-classification",
    model="cardiffnlp/twitter-roberta-base-sentiment-latest",
)

text = "I'm happy today!"


mv = registry.log_model(
    model=model,
    model_name="TWITTER_ROBERTA_BASE_SENTIMENT_LATEST",
)

mv.run(
    pd.DataFrame.from_records([{"text": text}]),
    # function_name="__call__", # Optional
)
Copy

텍스트 분류(다중 출력)

작업이 “text-clasification “ 또는 “sentiment-analysis”인 파이프라인으로, 여기서 top_k 는 숫자로 설정되며, 입력과 출력은 다음과 같습니다.

참고

텍스트 분류 작업은 top_k 가 임의의 숫자로 설정되어 있으면 그 숫자가 1이더라도 다중 출력으로 간주됩니다. 단일 출력 을 얻으려면 None의 top_k 값을 사용합니다.

입력

  • text: 분류할 문자열입니다.

  • text_pair: text 로 분류되는 문자열로, 텍스트 유사도를 계산하는 모델과 함께 사용됩니다. 모델에서 사용하지 않으면 비워둡니다.

예:

--------------------------------------------------------------------
|"text"                                              |"text_pair"  |
--------------------------------------------------------------------
|I am wondering if I should have udon or rice fo...  |             |
--------------------------------------------------------------------

출력

  • outputs: 결과 목록의 JSON 표현을 포함하는 문자열로, 각 목록에는 labelscore 등의 필드가 포함되어 있습니다.

예:

--------------------------------------------------------
|"outputs"                                             |
--------------------------------------------------------
|[{"label": "NEGATIVE", "score": 0.9987024068832397}]  |
--------------------------------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="text-classification",
    model="cardiffnlp/twitter-roberta-base-sentiment-latest",
    top_k=3,
)

text = "I'm happy today!"


mv = registry.log_model(
    model=model,
    model_name="TWITTER_ROBERTA_BASE_SENTIMENT_LATEST",
)

mv.run(
    pd.DataFrame.from_records([{"text": text}]),
    # function_name="__call__", # Optional
)
Copy

텍스트-텍스트 생성

작업이 “text2text-generation “ 인 파이프라인으로, 여기서 return_tensors 는 False 또는 설정 취소되며, 입력과 출력은 다음과 같습니다.

입력

  • inputs: 프롬프트가 포함된 문자열입니다.

예:

--------------------------------------------------------------------------------
|"inputs"                                                                      |
--------------------------------------------------------------------------------
|A descendant of the Lost City of Atlantis, who swam to Earth while saying, "  |
--------------------------------------------------------------------------------

출력

  • generated_text: num_return_sequences 가 1이면 생성된 텍스트를 포함하는 문자열, num_return_sequences가 1보다 크면 generated_text 를 포함한 필드를 포함하는 결과 사전의 JSON 목록을 문자열로 표현합니다.

예:

----------------------------------------------------------------
|"generated_text"                                              |
----------------------------------------------------------------
|, said that he was a descendant of the Lost City of Atlantis  |
----------------------------------------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="text2text-generation",
    model="google-t5/t5-small",
)

text = "Tell me a joke."


mv = registry.log_model(
    model=model,
    model_name="T5_SMALL",
)

mv.run(
    pd.DataFrame.from_records([{"inputs": text}]),
    # function_name="__call__", # Optional
)
Copy

참고

return_tensors 가 True인 텍스트-텍스트 생성 파이프라인은 지원되지 않습니다.

번역 생성

작업이 “번역 “ 인 파이프라인으로, 여기서 return_tensors 는 False 또는 설정 취소되며, 입력과 출력은 다음과 같습니다.

참고

return_tensors 가 True인 번역 생성 파이프라인은 지원되지 않습니다.

입력

  • inputs: 번역할 텍스트가 포함된 문자열입니다.

예:

------------------------------------------------------------------------------------------------------
|"inputs"                                                                                            |
------------------------------------------------------------------------------------------------------
|Snowflake's Data Cloud is powered by an advanced data platform provided as a self-managed service.  |
------------------------------------------------------------------------------------------------------

출력

  • translation_text: num_return_sequences 가 1인 경우 생성된 번역을 나타내는 문자열 또는 translation_text 등 필드가 각각 포함된 결과 사전의 JSON 목록을 나타내는 문자열입니다.

예:

---------------------------------------------------------------------------------------------------------------------------------
|"translation_text"                                                                                                             |
---------------------------------------------------------------------------------------------------------------------------------
|Le Cloud de données de Snowflake est alimenté par une plate-forme de données avancée fournie sous forme de service autogérés.  |
---------------------------------------------------------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="translation",
    model="deepvk/kazRush-kk-ru",
)

text = "Иттерді кім шығарды?"


mv = registry.log_model(
    model=model,
    model_name="KAZRUSH_KK_RU",
)

mv.run(
    pd.DataFrame.from_records([{"inputs": text}]),
    # function_name="__call__", # Optional
)
Copy

제로샷 분류

작업이 zero-shot-classification 인 파이프라인으로, 입력과 출력은 다음과 같습니다.

입력

  • sequences: 분류할 텍스트가 포함된 문자열입니다.

  • candidate_labels: 텍스트에 적용할 레이블이 포함된 문자열 목록입니다.

예:

-----------------------------------------------------------------------------------------
|"sequences"                                                       |"candidate_labels"  |
-----------------------------------------------------------------------------------------
|I have a problem with Snowflake that needs to be resolved asap!!  |[                   |
|                                                                  |  "urgent",         |
|                                                                  |  "not urgent"      |
|                                                                  |]                   |
|I have a problem with Snowflake that needs to be resolved asap!!  |[                   |
|                                                                  |  "English",        |
|                                                                  |  "Japanese"        |
|                                                                  |]                   |
-----------------------------------------------------------------------------------------

출력

  • sequence: 입력 문자열입니다.

  • labels: 적용된 레이블을 나타내는 문자열 목록입니다.

  • scores: 각 레이블에 대한 부동소수점 신뢰도 점수 목록입니다.

예:

--------------------------------------------------------------------------------------------------------------
|"sequence"                                                        |"labels"        |"scores"                |
--------------------------------------------------------------------------------------------------------------
|I have a problem with Snowflake that needs to be resolved asap!!  |[               |[                       |
|                                                                  |  "urgent",     |  0.9952737092971802,   |
|                                                                  |  "not urgent"  |  0.004726255778223276  |
|                                                                  |]               |]                       |
|I have a problem with Snowflake that needs to be resolved asap!!  |[               |[                       |
|                                                                  |  "Japanese",   |  0.5790848135948181,   |
|                                                                  |  "English"     |  0.42091524600982666   |
|                                                                  |]               |]                       |
--------------------------------------------------------------------------------------------------------------

텍스트 생성

작업이 “text-generation “ 인 파이프라인으로, 여기서 return_tensors 는 False 또는 설정 취소되며, 입력과 출력은 다음과 같습니다.

참고

return_tensors 가 True인 텍스트 생성 파이프라인은 지원되지 않습니다.

입력

  • inputs: 프롬프트가 포함된 문자열입니다.

예:

--------------------------------------------------------------------------------
|"inputs"                                                                      |
--------------------------------------------------------------------------------
|A descendant of the Lost City of Atlantis, who swam to Earth while saying, "  |
--------------------------------------------------------------------------------

출력

  • outputs: 결과 오브젝트 목록의 JSON을 나타내는 문자열로, 각 필드에는 generated_text 등의 필드가 포함됩니다.

예:

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|"outputs"                                                                                                                                                                                                 |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|[{"generated_text": "A descendant of the Lost City of Atlantis, who swam to Earth while saying, \"For my life, I don't know if I'm gonna land upon Earth.\"\n\nIn \"The Misfits\", in a flashback, wh...  |
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd

model = transformers.pipeline(
    task="text-generation",
    model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
)

mv = registry.log_model(
    model=model,
    model_name="TINYLLAMA",
)

text = "A descendant of the Lost City of Atlantis, who swam to Earth while saying,"
mv.run(
    pd.DataFrame.from_records([{"inputs": text}]),
    # function_name="__call__", # Optional
)
Copy

텍스트 생성(OpenAI 호환)

작업이 “text-generation “ 인 파이프라인으로, 여기서 return_tensors 는 False 또는 설정 취소되며, 입력과 출력은 다음과 같습니다.

모델 로깅 시 snowflake.ml.model.openai_signatures.OPENAI_CHAT_SIGNATURE 서명을 제공하면 해당 모델은 OpenAI API와 호환됩니다. 이를 통해 사용자는 모델에 openai.client.ChatCompletion 스타일 요청을 전달할 수 있습니다.

참고

return_tensors 가 True인 텍스트 생성 파이프라인은 지원되지 않습니다.

입력

  • messages: 모델로 보낼 메시지가 포함된 사전의 목록입니다.

  • max_completion_tokens: 생성할 최대 토큰 수입니다.

  • temperature: 생성에 사용할 온도입니다.

  • stop: 생성에 사용할 중지 시퀀스입니다.

  • n: 생성할 세대 수입니다.

  • stream: 생성을 스트리밍할지 여부입니다.

  • top_p: 생성에 사용할 상위 p 값입니다.

  • frequency_penalty: 생성에 사용할 빈도 패널티입니다.

  • presence_penalty: 생성에 사용할 현재 상태 패널티입니다.

예:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| messages                                                                                                                                                                                          |   max_completion_tokens |   temperature | stop   |   n | stream   |   top_p |   frequency_penalty |  presence_penalty |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| [{'role': 'system', 'content': 'Complete the sentence.'}, {'role': 'user', 'content': [{'type': 'text', 'text': 'A descendant of the Lost City of Atlantis, who swam to Earth while saying, '}]}] |                     250 |           0.9 |        |   3 | False    |       1 |                 0.1 |               0.2 |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

출력

  • outputs: 결과 오브젝트 목록의 JSON을 나타내는 문자열로, 각 필드에는 generated_text 등의 필드가 포함됩니다.

예:

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| id           | object          |     created | model                                      | choices                                                                                                                                      |  usage                                                               |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| chatcmpl-... | chat.completion | 1.76912e+09 | /shared/model/model/models/TINYLLAMA/model | [{'finish_reason': 'stop', 'index': 0, 'logprobs': None, 'message': {'content': 'The descendant is not actually ...', 'role': 'assistant'}}] | {'completion_tokens': 399, 'prompt_tokens': 52, 'total_tokens': 451} |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

코드 예제

import transformers
import pandas as pd
from snowflake.ml.model import openai_signatures

model = transformers.pipeline(
    task="text-generation",
    model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
)


mv = registry.log_model(
    model=model,
    model_name="TINYLLAMA",
    signatures=openai_signatures.OPENAI_CHAT_SIGNATURE,
)

# create a pd.DataFrame with openai.client.chat.completion arguments
x_df = pd.DataFrame.from_records(
    [
        {
            "messages": [
                {
                    "role": "system",
                    "content": [
                        {
                            "type": "text",
                            "text": "Complete the sentence.",
                        }
                    ],
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": "A descendant of the Lost City of Atlantis, who swam to Earth while saying, ",
                        }
                    ],
                },
            ],
            "max_completion_tokens": 250,
            "temperature": 0.9,
            "stop": None,
            "n": 3,
            "stream": False,
            "top_p": 1.0,
            "frequency_penalty": 0.1,
            "presence_penalty": 0.2,
        }
    ],
)

# OpenAI Chat Completion compatible output
output_df = mv.run(X=x_df)
Copy