Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
305 changes: 254 additions & 51 deletions README.md

Large diffs are not rendered by default.

Binary file modified assets/pipeline.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 1 addition & 4 deletions examples/hard_distillation/llm_span.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ def show_outputs(texts: list[str], preds: list[list[PredictedSpan]]):
for text, spans in zip(texts, preds, strict=True):
print(
text,
[
(s.text, pipeline.label_names[s.label], round(s.score, 2))
for s in spans
],
[(s.text, s.label, round(s.score, 2)) for s in spans],
)


Expand Down
2 changes: 1 addition & 1 deletion examples/hard_distillation/lmm_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
dog_url = "https://pngfre.com/wp-content/uploads/dog-poster.png"
images = [
PIL.Image.open(requests.get(url, stream=True).raw).convert("RGB")
for url in [cat_url, dog_url]
for url in [dog_url, cat_url]
]
label_set = ["cat", "dog"]

Expand Down
2 changes: 1 addition & 1 deletion examples/label_tuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
truths = [0] * 100 + [1] * 100

# Zero-shot prediction
preds = predict(input_embeddings, label_embeddings, torch.tensor([1.0]))
preds = predict(input_embeddings, label_embeddings)

# Train the label embeddings
training_output = label_tuning(
Expand Down
65 changes: 49 additions & 16 deletions examples/pipelines/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,65 @@

from delt import AudioPipeline

# Set your data and configure the encoder
bell = requests.get(
"https://soundcamp.org/sounds/382/RECEPTION_BELL_oVn.wav"
).content
morse = requests.get(
"https://soundcamp.org/sounds/382/morse_code_oscillator_-_medium_pitched_PTv.wav"
).content
audios = [bell, morse]

# Define a helper function to download audios
def download_audio(url: str) -> bytes:
"""Download an audio from a direct HTTP(S) URL and return it as bytes."""
return requests.get(url).content


# Instantiate the pipeline
label_verbalizations = {"bell": "bell", "morse": "morse"}
truths = [0, 1]
prompt_template = "That sound is a {}"
encoder_class = "clap"
encoder_name = "laion/larger_clap_music_and_speech"

# Instantiate the pipeline
pipeline = AudioPipeline(
encoder_name, encoder_class, label_verbalizations, prompt_template
)

# Zero-shot prediction
preds = pipeline.predict(audios, batch_size=8)
print(preds)
test_audios = [
download_audio("https://soundcamp.org/sounds/382/RECEPTION_BELL_oVn.wav"),
download_audio(
"https://soundcamp.org/sounds/382/morse_code_oscillator_-_low_pitched_NzH.wav"
),
]
preds = pipeline.predict(test_audios, batch_size=8)

# Label-tuning training
training_output = pipeline.fit(audios, truths)
train_audios = [
download_audio(
"https://soundcamp.org/sounds/382/BELL_TOLL_WITH_BARK_u78.wav"
),
download_audio(
"https://soundcamp.org/sounds/382/morse_code_oscillator_-_medium_pitched_PTv.wav"
),
]
train_truths = ["bell", "morse"]
training_output = pipeline.fit(train_audios, train_truths)

# Calibrate
calibration_audios = [
download_audio(
"https://soundcamp.org/sounds/382/BELL_AND_CAR_PASSING_BY_brO.wav"
),
download_audio(
"https://soundcamp.org/sounds/382/morse_code_oscillator_-_high_pitched_K29.wav"
),
]
calibration_truths = ["bell", "morse"]
calibrator = pipeline.calibrate(calibration_audios, calibration_truths)

# Prediction after training
preds = pipeline.predict(audios, batch_size=8)
print(preds)
preds = pipeline.predict(test_audios, batch_size=8)

# Evaluate
test_truths = ["bell", "morse"]
results = pipeline.evaluate(test_audios, test_truths, batch_size=8)

# Save the pipeline
pipeline.save("checkpoints/my-audio-model")

# Load the pipeline and predict again
pipeline = AudioPipeline.load("checkpoints/my-audio-model")
preds = pipeline.predict(test_audios, batch_size=8)
56 changes: 41 additions & 15 deletions examples/pipelines/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,51 @@

from delt import EmbeddingPipeline

# Define your input embeddings
input_embeddings = torch.vstack(
[torch.randn(100, 16), torch.randn(100, 16) + 2]
# Instantiate the pipeline
label_embeddings = torch.vstack(
[torch.randn(1, 16) - 3, torch.randn(1, 16) + 3]
)
pipeline = EmbeddingPipeline(
label_embeddings, label_names=["negative", "positive"]
)

# Zero-shot prediction
test_embeddings = torch.vstack(
[torch.randn(2, 16) - 3, torch.randn(2, 16) + 3]
)
preds = pipeline.predict(test_embeddings, batch_size=8)

# Label-tuning training
training_embeddings = torch.vstack(
[torch.randn(5, 16) - 3, torch.randn(5, 16) + 3]
)
training_truths = ["negative"] * 5 + ["positive"] * 5
training_output = pipeline.fit(
training_embeddings, training_truths, do_cv=False
)

# Define your label embeddings
label_embeddings = torch.vstack([torch.randn(1, 16), torch.randn(1, 16) + 2])
# Predict after training
preds = pipeline.predict(test_embeddings, batch_size=8)

# Define your truth labels
truths = [0] * 100 + [1] * 100
# Calibrate the probabilities with held-out data
calibration_embeddings = torch.vstack(
[torch.randn(5, 16) - 3, torch.randn(5, 16) + 3]
)
calibration_truths = ["negative"] * 5 + ["positive"] * 5
calibrator = pipeline.calibrate(
calibration_embeddings, calibration_truths, method="beta"
)

# Instantiate the pipeline
pipeline = EmbeddingPipeline(label_embeddings)
# Predict after calibration
preds = pipeline.predict(test_embeddings, batch_size=8)

# Zero-shot prediction
preds = pipeline.predict(input_embeddings, batch_size=8)
# Evaluate
test_truths = ["negative"] * 2 + ["positive"] * 2
results = pipeline.evaluate(test_embeddings, test_truths, batch_size=8)

# Label-tuning training
training_output = pipeline.fit(input_embeddings, truths, do_cv=True)
# Save the pipeline
pipeline.save("checkpoints/my-embedding-model")

# Prediction after training
preds = pipeline.predict(input_embeddings, batch_size=8)
# Load the pipeline and predict again
pipeline = EmbeddingPipeline.load("checkpoints/my-embedding-model")
preds = pipeline.predict(test_embeddings, batch_size=8)
62 changes: 49 additions & 13 deletions examples/pipelines/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,65 @@

from delt import ImagePipeline

# Set your data and configure the encoder
cat_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
dog_url = "https://pngfre.com/wp-content/uploads/dog-poster.png"
images = [
PIL.Image.open(requests.get(url, stream=True).raw).convert("RGB")
for url in [cat_url, dog_url]
]

# Define a helper function to download images
def download_image(url: str) -> PIL.Image.Image:
"""Download an image from a direct HTTP(S) URL and return it PIL Image."""
return PIL.Image.open(requests.get(url, stream=True).raw).convert("RGB")


# Instantiate the pipeline
label_verbalizations = {"cat": "cat", "dog": "dog"}
truths = [0, 1]

prompt_template = "The animal in the image is a {}"
encoder_class = "siglip"
encoder_name = "google/siglip2-base-patch16-naflex"

# Instantiate the pipeline
pipeline = ImagePipeline(
encoder_name, encoder_class, label_verbalizations, prompt_template
)

# Zero-shot prediction
preds = pipeline.predict(images, batch_size=8)
test_images = [
download_image("http://images.cocodataset.org/val2017/000000039769.jpg"),
download_image("https://pngfre.com/wp-content/uploads/dog-poster.png"),
]
preds = pipeline.predict(test_images, batch_size=8)

# Label-tuning training
training_output = pipeline.fit(images, truths)
train_images = [
download_image(
"https://images.pexels.com/photos/32557420/pexels-photo-32557420.jpeg"
),
download_image(
"https://images.pexels.com/photos/30074125/pexels-photo-30074125.jpeg"
),
]
train_truths = ["cat", "dog"]
training_output = pipeline.fit(train_images, train_truths)

# Calibrate
calibration_images = [
download_image(
"https://marketplace.canva.com/xHPJk/MAHA8XxHPJk/1/tl/canva-MAHA8XxHPJk.jpg"
),
download_image(
"https://static.vecteezy.com/system/resources/thumbnails/048/775/730/small/"
"cute-shih-tzu-dog-in-pink-sweatshirt-and-sunglasses-on-pastel-background-photo.jpg"
),
]
calibrate_truths = ["cat", "dog"]
calibrator = pipeline.calibrate(calibration_images, calibrate_truths)

# Prediction after training
preds = pipeline.predict(images, batch_size=8)
preds = pipeline.predict(test_images, batch_size=8)

# Evaluate
test_truths = ["cat", "dog"]
results = pipeline.evaluate(test_images, test_truths, batch_size=8)

# Save the pipeline
pipeline.save("checkpoints/my-image-model")

# Load the pipeline and predict again
pipeline = ImagePipeline.load("checkpoints/my-image-model")
preds = pipeline.predict(test_images, batch_size=8)
90 changes: 48 additions & 42 deletions examples/pipelines/span.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,11 @@ def show_outputs(texts: list[str], preds: list[list[PredictedSpan]]):
for text, spans in zip(texts, preds, strict=True):
print(
text,
[
(s.text, pipeline.label_names[s.label], round(s.score, 2))
for s in spans
],
[(s.text, s.label, round(s.score, 2)) for s in spans],
)


def annotate(gold: list[list[tuple[str, str]]]):
def annotate(texts: list[str], gold: list[list[tuple[str, str]]]):
"""Convert (phrase, label) pairs into span annotations."""

def annotate_span(text: str, phrase: str, label: str) -> SpanAnnotation:
Expand All @@ -30,46 +27,16 @@ def annotate_span(text: str, phrase: str, label: str) -> SpanAnnotation:
]


# Define your annotated data and label set
texts = [
"Alice visited Paris last summer.",
"Bob moved to Berlin in March.",
"Carol flew from Madrid to Rome.",
"David lives in London with Eve.",
"TransPerfect is located in Barcelona and it's aimed to translation and regionalization.",
"Google hired Maria to work on search in Zurich.",
"Microsoft released a new version of Windows last week.",
"The engineers at Siemens met John in Munich.",
"Amazon opened an office in Tokyo, and Sarah joined the AI team.",
"The package was shipped by Tesla to Peter in Oslo.",
]
gold = [
[("Alice", "person"), ("Paris", "location")],
[("Bob", "person"), ("Berlin", "location")],
[("Carol", "person"), ("Madrid", "location"), ("Rome", "location")],
[("David", "person"), ("London", "location"), ("Eve", "person")],
[("TransPerfect", "organization"), ("Barcelona", "location")],
[("Google", "organization"), ("Maria", "person"), ("Zurich", "location")],
[("Microsoft", "organization")],
[("Siemens", "organization"), ("John", "person"), ("Munich", "location")],
[("Amazon", "organization"), ("Tokyo", "location"), ("Sarah", "person")],
[("Tesla", "organization"), ("Peter", "person"), ("Oslo", "location")],
]
# Instantiate the pipeline
label_verbalizations = {
"person": "a person's name",
"location": "a city, country or place",
"organization": "a company or organization name",
}

# Annotate the input data
truths = annotate(gold)

# Set the encoder
prompt_template = "This is {}"
encoder_class = "sentence-transformer"
encoder_name = "sentence-transformers/all-MiniLM-L6-v2"

# Instantiate the pipeline
pipeline = SpanPipeline(
encoder_name,
encoder_class,
Expand All @@ -80,12 +47,51 @@ def annotate_span(text: str, phrase: str, label: str) -> SpanAnnotation:
)

# Zero-shot prediction
preds = pipeline.predict(texts, batch_size=8)
show_outputs(texts, preds)
test_texts = [
"Laura works for IBM in Dublin.",
"Nokia opened a lab in Helsinki.",
]
preds = pipeline.predict(test_texts, batch_size=8, threshold=0.8)
show_outputs(test_texts, preds)

# Label-tuning training
training_output = pipeline.fit(texts, truths)
train_texts = [
"Alice visited Paris last summer.",
"Bob moved to Berlin in March.",
"Carol flew from Madrid to Rome.",
"David lives in London with Eve.",
"TransPerfect is located in Barcelona and it's aimed to translation and regionalization.",
"Google hired Maria to work on search in Zurich.",
]
train_annotated_spans = [
[("Alice", "person"), ("Paris", "location")],
[("Bob", "person"), ("Berlin", "location")],
[("Carol", "person"), ("Madrid", "location"), ("Rome", "location")],
[("David", "person"), ("London", "location"), ("Eve", "person")],
[("TransPerfect", "organization"), ("Barcelona", "location")],
[("Google", "organization"), ("Maria", "person"), ("Zurich", "location")],
]
train_truths = annotate(train_texts, train_annotated_spans)
training_output = pipeline.fit(train_texts, train_truths)

# Predict after training
preds = pipeline.predict(test_texts, batch_size=8, threshold=0.8)
show_outputs(test_texts, preds)

# Evaluate
test_annotated_spans = [
[("Laura", "person"), ("IBM", "organization"), ("Dublin", "location")],
[("Nokia", "organization"), ("Helsinki", "location")],
]
test_truths = annotate(test_texts, test_annotated_spans)
results = pipeline.evaluate(
test_texts, test_truths, batch_size=8, threshold=0.8
)

# Save the pipeline
pipeline.save("checkpoints/my-span-model")

# Prediction after training
preds = pipeline.predict(texts, batch_size=8, threshold=0.8)
show_outputs(texts, preds)
# Load the pipeline and predict again
pipeline = SpanPipeline.load("checkpoints/my-span-model")
preds = pipeline.predict(test_texts, batch_size=8, threshold=0.8)
show_outputs(test_texts, preds)
Loading
Loading