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
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Applications where embeddings serve as persistent representations—such as sema

- 🚀 Perform **zero-shot classification** without training data.
- 🎯 Fine-tune classifiers using only a few labeled examples through **label tuning**.
- 🌍 Work across **text, images, audio, and video** using a unified API.
- 🌍 Work across **text (& spans), images, audio, and video** using a unified API.
- ⚡ Train in seconds by optimizing only lightweight label embeddings.
- 💻 Run inference efficiently on CPU once embeddings are available.
- 🤖 Distill powerful LLMs and multimodal models into compact, production-ready classifiers.
Expand Down Expand Up @@ -100,6 +100,7 @@ TYPESAFE_API_KEY=...
>
> `ffmpeg` is required for audio processing by `libtorchcodec`, which is used by the audio processors. Please install an `ffmpeg` version compatible with `torchaudio==2.10.0`. Versions 4, 5, 6, 7, and 8 are supported.
> Make sure `ffmpeg` is correctly installed and available in your `PATH` so that Torch can load it properly.
> MacOS users: if you installed `ffmpeg` through `homebrew` with a versioned formula, please, add the versioned path to your `zshrc` file, e.g., `export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/opt/ffmpeg@8/lib` and create a symlink as `ln -s /opt/homebrew/opt/ffmpeg@8 /opt/homebrew/opt/ffmpeg`

# 🚀 Pipeline example

Expand Down Expand Up @@ -167,12 +168,31 @@ training_output = pipeline.fit(input_embeddings, truths)
preds = pipeline.predict(input_embeddings, batch_size=8)
```

# 🧩 Span detection and classification

`SpanPipeline` extends text label tuning to span tasks such as NER or aspect-based sentiment analysis. Rather than BIO tagging, which would add `B-`/`I-` noise to the label embeddings, every contiguous span of up to `max_span_width` words is a candidate. Each text is encoded once, and each candidate is embedded as the mean of its contextual token embeddings and classified against the label embeddings, plus a trainable "none" class for candidates that are not spans of interest. Predicted spans never overlap. See the [span example](examples/pipelines/span.py).

```python
from delt import SpanPipeline
from delt.pipelines.text import SpanAnnotation

pipeline = SpanPipeline(
"sentence-transformers/all-MiniLM-L6-v2",
"sentence-transformer",
{"person": "a person name", "location": "a place name"},
"This is {}",
)
# `truths` has one list of `SpanAnnotation(start, end, label)` per text (character offsets, `end` exclusive)
pipeline.fit(texts, truths)
spans = pipeline.predict(texts, threshold=0.5) # list[list[PredictedSpan]]
```


# 🧪 Distillation example

Instead of manually annotating thousands of examples, a stronger model can act as a **teacher**, while `delt` learns a lightweight **student**.

Both **soft** and **hard** distillation are supported by `delt`. You can take a look to the [soft distillation](src/delt/examples/soft_distillation/) and [hard distillation](src/delt/examples/hard_distillation/) folders to see how it works. Here we show an example to distill `gpt-5.4-nano` into label embeddings for a sentiment analysis task:
Both **soft** and **hard** distillation are supported by `delt` for every modality, including text span classification. You can take a look to the [soft distillation](src/delt/examples/soft_distillation/) and [hard distillation](src/delt/examples/hard_distillation/) folders to see how it works. Here we show an example to distill `gpt-5.4-nano` into label embeddings for a sentiment analysis task:

```python
from delt.pipelines import TextPipeline
Expand Down Expand Up @@ -218,7 +238,6 @@ training_output = pipeline.fit(texts, truths)
preds = pipeline.predict(texts, batch_size=8)
```


# 🖥 User Interface

`delt` ships with a lightweight Streamlit application for experimentation.
Expand Down
10 changes: 5 additions & 5 deletions dev-tools/format.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ set -x
# Limit line length to 79 characters (PEP 8)
uv run ruff format \
--line-length 79 \
src/delt tests
src/delt tests examples

# Sort imports (isort)
uv run ruff check \
--select I \
--fix \
src/delt tests
src/delt tests examples

# Remove unused imports and variables
uv run ruff check \
--select F401,F841,C901 \
--fix \
src/delt tests
src/delt tests examples

# Check docstring conventions
uv run ruff check \
--select D \
--ignore D203,D212 \
--fix \
src/delt tests
src/delt tests examples

# Auto-fix other common issues
uv run ruff check \
--fix \
src/delt tests
src/delt tests examples
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
)

# Generate the labels (`predict`) or probs (`predict_proba`)
truth_probas = teacher.predict_proba(texts, label_set)
truth_probas = teacher.predict(texts, label_set)

# Create the label verbalizations (same order as the label set)
label_verbalizations = {
Expand Down
86 changes: 86 additions & 0 deletions examples/hard_distillation/llm_span.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Example script for the text span pipeline with LLM distillation."""

from delt.pipelines import SpanPipeline
from delt.pipelines.text.span import PredictedSpan, SpanAnnotation
from delt.teachers import LLMSpanTextTeacher


# Define some helper functions
def show_outputs(texts: list[str], preds: list[list[PredictedSpan]]):
"""Print the predicted spans for each text."""
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
],
)


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

def annotate_span(text: str, phrase: str, label: str) -> SpanAnnotation:
start = text.index(phrase)
return SpanAnnotation(start, start + len(phrase), label)

return [
[annotate_span(text, phrase, label) for phrase, label in spans]
for text, spans in zip(texts, silver, strict=True)
]


# Define your input data and label set
texts = [
"Apple is a worldwide company.",
"The AIRD team of TransPerfect is comprised of members like Ian, Celia, Mahmoud, YanRu and Llorenç.",
]
label_set = ["person", "company", "team"]

# Instantiate the teacher model
teacher = LLMSpanTextTeacher(
"gpt-5.4-nano",
{"temperature": 0},
"Extract the named entities from the following text.",
)

# Generate the span silver labels (only `predict` is supported)
silver = teacher.predict(texts, label_set)

# Create the label verbalizations (same order as the label set)
label_verbalizations = {
"person": "a person's name",
"company": "a company name",
"team": "an internal team of a company",
}


# Annotate the input data
truths = annotate(silver)

# 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,
label_verbalizations,
prompt_template,
max_span_width=8,
negative_ratio=3,
)

# Zero-shot prediction
preds = pipeline.predict(texts, batch_size=8)
show_outputs(texts, preds)

# Label-tuning training
training_output = pipeline.fit(texts, truths)

# Prediction after training
preds = pipeline.predict(texts, batch_size=8, threshold=0.8)
show_outputs(texts, preds)
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
teacher = LLMTextTeacher(
"gpt-5.4-nano",
{"temperature": 0},
"Classify the following texts into positive or negative for a sentiment analysis task.",
"Classify the following text into positive or negative for a sentiment analysis task.",
)

# Generate the labels (`predict`) or probs (`predict_proba`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
teacher = LMMAudioTeacher(
"gemini/gemini-3.5-flash",
{"temperature": 0},
"Classify the following texts into bell or morse",
"Classify the following audio into bell or morse",
)

# Generate the labels (`predict`) or probs (`predict_proba`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
teacher = LMMImageTeacher(
"gemini/gemini-3.5-flash",
{"temperature": 0},
"Classify the following images into cat or dog.",
"Classify the following image into cat or dog.",
)

# Generate the labels (`predict`) or probs (`predict_proba`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def download_video(url: str) -> bytes:
teacher = LMMVideoTeacher(
"gemini/gemini-3.5-flash",
{"temperature": 0},
"Classify the following videos into fake or real.",
"Classify the following video into fake or real.",
)

# Generate the labels (`predict`) or probs (`predict_proba`)
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
91 changes: 91 additions & 0 deletions examples/pipelines/span.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""Example of span detection and classification with label tuning."""

from delt import SpanPipeline
from delt.pipelines.text import PredictedSpan, SpanAnnotation


# Define some helper functions
def show_outputs(texts: list[str], preds: list[list[PredictedSpan]]):
"""Print the predicted spans for each text."""
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
],
)


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

def annotate_span(text: str, phrase: str, label: str) -> SpanAnnotation:
start = text.index(phrase)
return SpanAnnotation(start, start + len(phrase), label)

return [
[annotate_span(text, phrase, label) for phrase, label in spans]
for text, spans in zip(texts, gold, strict=True)
]


# 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")],
]
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,
label_verbalizations,
prompt_template,
max_span_width=8,
negative_ratio=3,
)

# Zero-shot prediction
preds = pipeline.predict(texts, batch_size=8)
show_outputs(texts, preds)

# Label-tuning training
training_output = pipeline.fit(texts, truths)

# Prediction after training
preds = pipeline.predict(texts, batch_size=8, threshold=0.8)
show_outputs(texts, preds)
File renamed without changes.
File renamed without changes.
52 changes: 52 additions & 0 deletions examples/soft_distillation/jev_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Example script soft distillation with Jev."""

import os

from dotenv import load_dotenv

from delt.pipelines import TextPipeline
from delt.teachers import JevTextTeacher

load_dotenv()

# Define your input data and label set
texts = ["I hate you", "I love you"]
label_set = ["positive", "negative"]

# Instantiate the teacher model (through OpenRouter, although any provider is supported)
teacher = JevTextTeacher(
"jev-latest",
"What is the sentiment of this text?",
"User text: {}",
base_url="https://openrouter.ai/api",
api_key=os.environ["OPENROUTER_API_KEY"],
)

# Generate the labels (`predict`) or probs (`predict_proba`)
truth_probas = teacher.predict_proba(texts, label_set)

# Create the label verbalizations (same order as the label set)
label_verbalizations = {
"positive": "really positive",
"negative": "really negative",
}

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

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

# Zero-shot prediction
preds = pipeline.predict(texts, batch_size=8)

# Label-tuning to train the student model
training_output = pipeline.fit(texts, truth_probas)

# Prediction after training
preds = pipeline.predict(texts, batch_size=8)
print(preds)
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ where = ["src"]

[project]
name = "deltpy"
version = "1.6.2"
version = "1.7.2"
description = "A Python framework for Label Tuning of Multimodal Dual Encoders."
readme = "README.md"
requires-python = ">=3.10,<3.12"
Expand Down Expand Up @@ -67,3 +67,6 @@ dev = [
[tool.mypy]
ignore_missing_imports = true
disable_error_code = "import-untyped"

[tool.ruff.lint]
extend-safe-fixes = ["RUF022"]
Loading
Loading