/
PayloadLogging.py
207 lines (168 loc) · 6.01 KB
/
PayloadLogging.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# Databricks notebook source
# import libraries
import os
import requests
import numpy as np
import pandas as pd
import json
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types import DataType, Schema, ColSpec
from mlflow.tracking import MlflowClient
# COMMAND ----------
# Define constants
endpoint_name = "CallEndpoint" # endpoint name of the cpu endpoint
model_name = "CPUWrapper" # model name that will be deployed to cpu endpoint
dbfs_table_path = "dbfs:/llm" # location of the inference table
os.environ["URI"] = dbutils.secrets.get(scope="llm", key="endpoint_uri") # endpoint uri of the gpu endpoint
os.environ["TOKEN"] = dbutils.secrets.get(scope="llm", key="endpoint_token") # token to access the gpu endpoint
# COMMAND ----------
class CallEndpoint(mlflow.pyfunc.PythonModel):
def __init__(self):
self.url = os.environ["URI"]
self.headers = {'Authorization': f'Bearer {os.environ["TOKEN"]}', 'Content-Type': 'application/json'}
self.session = requests.Session()
def create_tf_serving_json(self, data):
return {'inputs': {name: data[name].tolist() for name in data.keys()} if isinstance(data, dict) else data.tolist()}
def score_model(self, dataset):
if isinstance(dataset, pd.DataFrame):
ds_dict = {'dataframe_records': dataset.to_dict(orient='records')}
else:
ds_dict = self.create_tf_serving_json(dataset)
data_json = json.dumps(ds_dict, allow_nan=True)
response = self.session.post(url=self.url, headers=self.headers, data=data_json)
if response.status_code != 200:
raise Exception(f'Request failed with status {response.status_code}, {response.text}')
return response.json()
def predict(self, context, model_input):
#change this logic as per your requirement
return self.score_model(model_input)['predictions']
# COMMAND ----------
# Log the model
# Change schema as desired
input_schema = Schema([
ColSpec(DataType.string, "prompt", optional= True),
ColSpec(DataType.double, "temperature", optional= True),
ColSpec(DataType.long, "max_tokens", optional= True)])
output_schema = Schema([ColSpec(DataType.string)])
signature = ModelSignature(inputs=input_schema, outputs=output_schema)
# Define an input example for your use case
input_example=pd.DataFrame({"prompt":["what is Machine Learning?"],
"temperature": [0.0],
"max_tokens": [100]})
with mlflow.start_run() as run:
mlflow.pyfunc.log_model(
"model",
python_model=CallEndpoint(),
registered_model_name=model_name,
signature=signature,
input_example=input_example,
)
# COMMAND ----------
# Offline test
loaded_model = mlflow.pyfunc.load_model("runs:/" + run.info.run_id+'/model')
loaded_model.predict(input_example)
# COMMAND ----------
# Create an endpoint with infernece table
API_ROOT = dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiUrl().get()
API_TOKEN = dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get()
client = MlflowClient()
url = f"{API_ROOT}/api/2.0/serving-endpoints"
headers = {"Authorization": f"Bearer {API_TOKEN}", "Content-Type": "application/json"}
data = {
"name": endpoint_name,
"config": {
"served_models": [
{
"model_name": model_name,
"model_version": client.get_registered_model(model_name).latest_versions[0].version,
"workload_size": "Small",
"scale_to_zero_enabled": True,
"environment_vars": {
"URI": "{{secrets/llm/endpoint_uri}}",
"TOKEN": "{{secrets/llm/endpoint_token}}"
}
}
]
},
"inference_table_config": {
"dbfs_destination_path": dbfs_table_path
}
}
headers = {
"Context-Type": "text/json",
"Authorization": f"Bearer {API_TOKEN}"
}
response = requests.post(
url,
json=data,
headers=headers
)
print("Response status:", response.status_code)
print("Reponse text:", response.text)
# COMMAND ----------
# Get endpoint status
data = {
"name": endpoint_name
}
headers = {
"Context-Type": "text/json",
"Authorization": f"Bearer {API_TOKEN}"
}
response = requests.get(
url=f"{API_ROOT}/api/2.0/preview/serving-endpoints/{endpoint_name}",
json=data,
headers=headers
)
print(response.status_code, response.text)
# COMMAND ----------
# Online test
data = {
"dataframe_records":
[
{"prompt":"what is Machine Learning?",
"temperature": 0.0,
"max_tokens": 75}
],
"inference_id": "123qwe"
}
headers = {
"Authorization": f"Bearer {API_TOKEN}",
}
response = requests.post(
url=f"{API_ROOT}/serving-endpoints/{endpoint_name}/invocations",
json=data,
headers=headers
)
print("Response status:", response.status_code)
print("Reponse text:", response.text)
# COMMAND ----------
# Online test
data = {
"dataframe_records":
[
{"prompt":"what is Machine Learning?",
"temperature": 0.0,
"max_tokens": 75,
"feedback": "Machine learning is a branch of artificial intelligence that involves the development of algorithms that can learn from and make predictions or decisions based on data. It's used in various applications like speech recognition, recommendation systems, and image classification."}
],
"inference_id": "123qwe"
}
headers = {
"Authorization": f"Bearer {API_TOKEN}",
}
response = requests.post(
url=f"{API_ROOT}/serving-endpoints/{endpoint_name}/invocations",
json=data,
headers=headers
)
print("Response status:", response.status_code)
print("Reponse text:", response.text)
# COMMAND ----------
#Query your raw Inference Log Delta table!
# Note: A log will arrive in your Inference Table about 5-10 minutes after the model invocation.
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
df = spark.sql(f"select * from delta.`{dbfs_table_path}/{endpoint_name}` limit 1000")
display(df)
# COMMAND ----------