Pular para o conteúdo principal

Registrar e servir um modelo de embedding OSS

Este notebook configura o modelo de incorporação de texto de código aberto e5-small-v2 em um endpoint de Model Serving utilizável para AI Search.

  • Baixe o modelo do Hugging Face Hub.
  • Registrar no MLflow Model Registry.
  • Inicie um endpoint de Model Serving para servir o modelo.

O modelo e5-small-v2 está disponível em https://huggingface.co/intfloat/e5-small-v2.

Para uma lista de versões de biblioteca incluídas no Databricks Runtime, consulte as notas sobre a versão para sua versão do Databricks Runtime.

Instalar o SDK do Databricks para Python

Este Notebook usa seu cliente Python para trabalhar com endpoints de disponibilização.

Python
%pip install -U databricks-sdk python-snappy
%pip install sentence-transformers
dbutils.library.restartPython()

Baixar modelo

Python
# Download model using the sentence_transformers library.
from sentence_transformers import SentenceTransformer

source_model_name = 'intfloat/e5-small-v2' # model name on Hugging Face Hub
model = SentenceTransformer(source_model_name)
Python
# Test the model, just to show it works.
sentences = ["This is an example sentence", "Each sentence is converted"]
embeddings = model.encode(sentences)
print(embeddings)

Registrar modelo no MLflow

Python
import mlflow
mlflow.set_registry_uri("databricks-uc")
Python

# Specify the catalog and schema to use. You must have USE_CATALOG privilege on the catalog and USE_SCHEMA and CREATE_TABLE privileges on the schema.
# Change the catalog and schema here if necessary.
catalog = "main"
schema = "default"
model_name = "e5-small-v2"
Python
# MLflow model name. The Model Registry uses this name for the model.
registered_model_name = f"{catalog}.{schema}.{model_name}"
Python
# Compute input and output schema.
signature = mlflow.models.signature.infer_signature(sentences, embeddings)
print(signature)
Python
model_info = mlflow.sentence_transformers.log_model(
model,
artifact_path="model",
signature=signature,
input_example=sentences,
registered_model_name=registered_model_name)
Python
inference_test = ["I enjoy pies of both apple and cherry.", "I prefer cookies."]

# Load the custom model by providing the URI for where the model was logged.
loaded_model_pyfunc = mlflow.pyfunc.load_model(model_info.model_uri)

# Perform a quick test to ensure that the loaded model generates the correct output.
embeddings_test = loaded_model_pyfunc.predict(inference_test)
embeddings_test
Python
# Extract the version of the model you just registered.
mlflow_client = mlflow.MlflowClient()

def get_latest_model_version(model_name):
client = mlflow_client
model_version_infos = client.search_model_versions("name = '%s'" % model_name)
return max([int(model_version_info.version) for model_version_info in model_version_infos])

model_version = get_latest_model_version(registered_model_name)
model_version

Criar endpoint de servindo modelo

Para obter mais detalhes, consulte Criar endpoints de servindo modelo de base.

Observação: Este exemplo cria um pequeno endpoint de CPU que é dimensionado para 0. Isso é para testes rápidos e pequenos. Para casos de uso mais realistas, considere usar endpoint de GPU para computação de embeddings mais rápida e não reduzir para 0 se você esperar consultas frequentes, já que os endpoint de Model Serving têm alguma sobrecarga de inicialização a frio.

Python
endpoint_name = "e5-small-v2"  # Name of endpoint to create
Python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import EndpointCoreConfigInput

w = WorkspaceClient()
Python
endpoint_config_dict = {
"served_entities": [
{
"name": f'{registered_model_name.replace(".", "_")}_{1}',
"entity_name": registered_model_name,
"entity_version": model_version,
"workload_type": "CPU",
"workload_size": "Small",
"scale_to_zero_enabled": True,
}
]
}

endpoint_config = EndpointCoreConfigInput.from_dict(endpoint_config_dict)

# The endpoint may take several minutes to get ready.
w.serving_endpoints.create_and_wait(name=endpoint_name, config=endpoint_config)

Endpoint da query

O comando create_and_wait acima aguarda até que o endpoint esteja pronto. Você também pode verificar o status do endpoint de disponibilização na interface do usuário do Databricks.

Para obter mais informações, consulte Consultar modelos básicos.

Python
# Only run this command after the Model Serving endpoint is in the Ready state.
import time

start = time.time()

# If the endpoint is not yet ready, you might get a timeout error. If so, wait and then rerun the command.
endpoint_response = w.serving_endpoints.query(name=endpoint_name, dataframe_records=['Hello world', 'Good morning'])

end = time.time()

print(endpoint_response)
print(f'Time taken for querying endpoint in seconds: {end-start}')

Notebook de exemplo

Registrar e servir um modelo de incorporação de código aberto

Abrir notebook em uma nova aba