To create a model adapter for Palantir Foundry, you'll need to follow these steps:
- Install necessary packages:
First, make sure you have the following libraries installed:
pip install transformers
pip install palantir-foundry-sdk
- Define the BERT model adapter class:
Create a Python class that extends Foundry's
ModelAdapter class and implements the required methods to handle BERT model input and output. In this example, I'll assume you want to perform a simple text classification task.
import torch
from transformers import BertTokenizer, BertForSequenceClassification
from palantir_foundry.model_adapters import ModelAdapter, ModelInput, ModelOutput
class BertClassifierAdapter(ModelAdapter):
def __init__(self, model_name: str = "bert-base-uncased", num_labels: int = 2):
self.tokenizer = BertTokenizer.from_pretrained(model_name)
self.model = BertForSequenceClassification.from_pretrained(model_name, num_labels=num_labels)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model.to(self.device)
def input_from_dict(self, input_dict: dict) -> ModelInput:
input_text = input_dict["text"]
inputs = self.tokenizer(input_text, padding=True, truncation=True, max_length=512, return_tensors="pt")
inputs = {k: v.to(self.device) for k, v in inputs.items()}
return ModelInput(inputs)
def predict(self, input: ModelInput) -> ModelOutput:
with torch.no_grad():
outputs = self.model(**input.data)
logits = outputs.logits.detach().cpu().numpy()
probabilities = torch.softmax(outputs.logits, dim=1).detach().cpu().numpy()
prediction = np.argmax(probabilities)
return ModelOutput({"logits": logits, "prediction": prediction, "probabilities": probabilities.tolist()})
def output_to_dict(self, output: ModelOutput) -> dict:
return {
"logits": output.logits.tolist(),
"prediction": output.prediction,
"probability": output.probabilities[0][output.prediction],
}
- Configure and register the adapter:
In your Foundry project, create a
.foundry.yml file in the root directory with the following content:
models:
- name: bert_classifier
type: python
module: path.to.your.model_adapter:BertClassifierAdapter
Replace path.to.your.model_adapter with the actual path to the Python file containing the BertClassifierAdapter class.
- Deploy the model:
Now you can deploy the model to Foundry using the command line:
foundry push models
After deployment, you can use the bert_classifier model for prediction tasks within Palantir Foundry.
Remember that this is a basic example for text classification. Depending on your specific use case, you may need to modify the input preprocessing, output handling, or the model architecture itself.