Files
prob_jsonformer/example.ipynb
T

16 KiB

In [1]:
# autoreload your package
%load_ext autoreload
%autoreload 2
In [2]:
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

print("Loading model and tokenizer...")
model_name = "databricks/dolly-v2-3b"
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    use_cache=True,
    torch_dtype=torch.float16,
    attn_implementation='eager',
).to("cuda:0")
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True, use_cache=True)
print("Loaded model and tokenizer")
/media/wassname/SGIronWolf/projects5/2024/prob_jsonformer/.venv/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
Loading model and tokenizer...
/media/wassname/SGIronWolf/projects5/2024/prob_jsonformer/.venv/lib/python3.9/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(
/media/wassname/SGIronWolf/projects5/2024/prob_jsonformer/.venv/lib/python3.9/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
Loaded model and tokenizer

Continue

In [4]:
from prob_jsonformer.format import highlight_values
from prob_jsonformer.main import Jsonformer

ecomm = {
    "type": "object",
    "properties": {
        "store": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "location": {"type": "string"},
                "choice_probs": {"type": "choice_probs", "enum": ["ski", "snowboard", "walk", "pretend"]},
                "inventory": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "productId": {"type": "string"},
                            "name": {"type": "string"},
                            "description": {"type": "string"},
                            "category": {"type": "string"},
                            "price": {"type": "number"},
                            "inStock": {"type": "boolean"},
                            "rating": {"type": "number"},
                            "images": {"type": "array", "items": {"type": "string"}},
                        },
                    },
                },
            },
        }
    },
}


builder = Jsonformer(
    model=model,
    tokenizer=tokenizer,
    json_schema=ecomm,
    prompt="write a description about mike's ski shop which sells premium skis and snowboards",
    max_string_token_length=20,
)

print("Generating...")
output = builder()

highlight_values(output)
Generating...
{
  store: {
    name: "Mike's Ski Shop",
    location: "Somewhere",
    choice_probs: [
      {
        prob: 0.01739501953125,
        choice: "pretend"
      },
      {
        prob: 0.002094268798828125,
        choice: "snowboard"
      },
      {
        prob: 0.0007467269897460938,
        choice: "walk"
      },
      {
        prob: 0.97998046875,
        choice: "ski"
      }
    ],
    inventory: [
      {
        productId: "1",
        name: "Snowboard X-15",
        description: "Snowboard for all levels",
        category: "Snowboards",
        price: 20.0,
        inStock: True,
        rating: 5.0,
        images: [
          "https://s3.amazonaws.com/mikesskisport/images/Snow"
        ]
      },
      {
        productId: "2",
        name: "Mike's Ski Shop Exclusive",
        description: "Mike's Ski Shop Exclusive",
        category: "Ski Shops",
        price: 20.0,
        inStock: True,
        rating: 5.0,
        images: [
          "https://s3.amazonaws.com/mikesskisport/images/Mike"
        ]
      },
      {
        productId: "3",
        name: "Mike's Ski Shop Exclusive",
        description: "Mike's Ski Shop Exclusive",
        category: "Ski Shops",
        price: 20.0,
        inStock: True,
        rating: 5.0,
        images: [
          "https://s3.amazonaws.com/mikesskisport/images/Mike"
        ]
      }
    ]
  }
}
In [ ]:
car = {
    "type": "object",
    "properties": {
        "make": {"type": "string"},
        "model": {"type": "choice_probs", "enum": ["Mazda", "Kea"]},
        "new": {"type": "choice_probs", "enum": ["true", "false"]},
        "rating": {"type": "choice_probs", "enum": ["1", "2", "3", "4"]},
        "year": {"type": "number"},
        "colors_available": {
            "type": "array",
            "items": {"type": "string"},
        },
    },
}

builder = Jsonformer(
    model=model,
    tokenizer=tokenizer,
    json_schema=car,
    prompt="generate an example car",
)

print("Generating...")
output = builder()

highlight_values(output)
In [ ]:
complex_car = {
    "type": "object",
    "properties": {
        "car": {
            "type": "object",
            "properties": {
                "make": {"type": "string"},
                "model": {"type": "string"},
                "year": {"type": "number"},
                "colors": {"type": "choice_probs", "enum": ["red", "green", "blue", "black", "white"]},
                "as_new": {"type": "choice_probs", "enum": ["true", "false"]},
                "rating": {"type": "choice_probs", "enum": ["1", "2", "3", "4"]},
                "features": {
                    "type": "object",
                    "properties": {
                        "audio": {
                            "type": "object",
                            "properties": {
                                "brand": {"type": "string"},
                                "speakers": {"type": "number"},
                                "hasBluetooth": {"type": "boolean"},
                            },
                        },
                        "safety": {
                            "type": "object",
                            "properties": {
                                "airbags": {"type": "number"},
                                "parkingSensors": {"type": "boolean"},
                                "laneAssist": {"type": "boolean"},
                            },
                        },
                        "performance": {
                            "type": "object",
                            "properties": {
                                "engine": {"type": "string"},
                                "horsepower": {"type": "number"},
                                "topSpeed": {"type": "number"},
                            },
                        },
                    },
                },
            },
        },
        "owner": {
            "type": "object",
            "properties": {
                "firstName": {"type": "string"},
                "lastName": {"type": "string"},
                "age": {"type": "number"},
            },
        },
    },
}
builder = Jsonformer(
    model=model,
    tokenizer=tokenizer,
    json_schema=complex_car,
    prompt="generate an example Rolls Royce Phantom",
)

print("Generating...")
output = builder()

highlight_values(output)

Readme example

In [22]:
from prob_jsonformer import Jsonformer
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "databricks/dolly-v2-3b"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

json_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "age_probs": {"type": "choice_probs", "enum": [str(s) for s in range(10, 30)]},
        "unit_time": {"type": "number"},
        "is_student": {"type": "boolean"},
        "is_student_probs": {"type": "choice_probs", "enum": ["true", "false"]},
        "courses": {
            "type": "array",
            "items": {"type": "string"}
        },
        "trim": {"type": ["string", "null"]},
        "color": {
            "type": "enum",
            "values": ["red", "green", "blue", "brown", "white", "black"],
        },
    }
}

prompt = "Generate a young person's information based on the following schema:"
jsonformer = Jsonformer(model, tokenizer, json_schema, prompt, temperature=0)
generated_data = jsonformer()

generated_data
Out [22]:
{'name': 'John Doe',
 'age': 20,
 'age_probs': [{'prob': 0.794921875, 'choice': '12'},
  {'prob': 0.068359375, 'choice': '10'},
  {'prob': 0.04345703125, 'choice': '16'},
  {'prob': 0.03228759765625, 'choice': '14'},
  {'prob': 0.0175628662109375, 'choice': '11'},
  {'prob': 0.0157318115234375, 'choice': '15'},
  {'prob': 0.013671875, 'choice': '20'},
  {'prob': 0.006664276123046875, 'choice': '18'},
  {'prob': 0.0046539306640625, 'choice': '13'},
  {'prob': 0.0018215179443359375, 'choice': '21'},
  {'prob': 0.00041294097900390625, 'choice': '17'},
  {'prob': 0.00028824806213378906, 'choice': '19'},
  {'prob': 0.00014495849609375, 'choice': '22'},
  {'prob': 6.955862045288086e-05, 'choice': '23'},
  {'prob': 2.968311309814453e-05, 'choice': '25'},
  {'prob': 2.8789043426513672e-05, 'choice': '26'},
  {'prob': 1.901388168334961e-05, 'choice': '24'},
  {'prob': 1.1742115020751953e-05, 'choice': '28'},
  {'prob': 1.1920928955078125e-06, 'choice': '27'},
  {'prob': 7.748603820800781e-07, 'choice': '29'}],
 'unit_time': 0.01,
 'is_student': True,
 'is_student_probs': [{'prob': 0.8310546875, 'choice': 'true'},
  {'prob': 0.1688232421875, 'choice': 'false'}],
 'courses': ['C1'],
 'trim': None,
 'color': 'white'}
In [ ]:
In [ ]: