pntx
pntx is a Python library that turns user-supplied positive/negative text pools
into two independent components:
pntx.t2pn(text → positive/negative) — a family of scikit-learnClassifiers that label arbitrary text aspositiveornegative:LLMPromptingClassifierclassifies via LLM few-shot prompting/scoring (no training), andFineTuningClassifieractually fine-tunes a pretrainedtransformersencoder (default: multilingual BERT).pntx.pn2t(positive/negative → text) — two imbalanced-learn-style over-samplers with different goals:HardPositiveOverSamplergenerates "hard positive" text to balance an imbalanced dataset for classifier training, andTypicalPositiveOverSamplergenerates typical, representative positives with specific details generalized away, for publishing a stand-in for data you can't share as-is.
The meaning of "positive" and "negative" is entirely up to you. It doesn't have to be
sentiment — it can be formal/casual, policy-compliant/violating, or any other contrast
you define with examples. pntx never interprets the pools; it only uses them as
few-shot and scoring material.
from pntx.t2pn import LLMPromptingClassifier
from pntx.pn2t import HardPositiveOverSampler
# --- t2pn: classification via LLM few-shot prompting (no training) ---
clf = LLMPromptingClassifier(backend="llama", backend_kwargs={"model_path": "model.gguf"})
X = ["The movie was fantastic", "Support was quick and helpful",
"The movie was boring", "Support was slow and unhelpful"]
y = ["positive", "positive", "negative", "negative"] # 0/1 works too
clf.fit(X, y)
clf.predict(["The staff were incredibly friendly"]) # array(['positive'], dtype='<U8')
clf.predict_proba(["The staff were incredibly friendly"]) # shape (1, 2), columns follow clf.classes_
# drops straight into the scikit-learn ecosystem
from sklearn.model_selection import cross_val_score
cross_val_score(clf, X, y, cv=5)
# persist the fitted pools (not the backend -- pass a fresh one back in on load)
clf.save("classifier.json")
loaded = LLMPromptingClassifier.load("classifier.json", backend="llama",
backend_kwargs={"model_path": "model.gguf"})
# --- t2pn: classification via fine-tuning a pretrained encoder (pntx[finetuning]) ---
from pntx.t2pn import FineTuningClassifier
ft_clf = FineTuningClassifier(class_weight="balanced") # default model_name is multilingual BERT
ft_clf.fit(X, y) # this one actually trains
ft_clf.predict_proba(["The staff were incredibly friendly"])
ft_clf.save("finetuned/") # persists the trained weights, not just pooled text
loaded_ft = FineTuningClassifier.load("finetuned/")
# --- pn2t: hard-positive generation (an imbalanced-learn-style over-sampler) ---
sampler = HardPositiveOverSampler(
backend="llama",
backend_kwargs={"model_path": "model.gguf"},
sampling_strategy="auto", # default: generate positives until classes balance
random_state=0,
)
X_aug, y_aug = sampler.fit_resample(X, [1, 1, 0, 0]) # binary labels only; positive class = 1
sampler.generation_result_.hard_positives # generated texts + the LLM's rationale for each
# --- pn2t: typical-positive generation for publishable stand-in data ---
from pntx.pn2t import TypicalPositiveOverSampler
synth = TypicalPositiveOverSampler(
backend="llama",
backend_kwargs={"model_path": "model.gguf"},
sampling_strategy={1: 2 + 10}, # required: 2 existing positives + 10 new ones
)
X_syn, y_syn = synth.fit_resample(X, [1, 1, 0, 0])
synth.generation_result_.synthetic_texts # generated texts + what was generalized away for each
HardPositiveOverSampler.fit_resample generates "hard positives" — texts an expert would label
positive but that shallow classifiers or untrained humans might mislabel negative — by
first asking the backend to analyze what distinguishes the two classes. It's a full
port of semaxis's class of the same name,
routed through pntx's own Backend abstraction so it can share a loaded model with
LLMPromptingClassifier instead of loading its own. v1 only generates the positive side and
supports binary labels only (0/1, -1/1, "positive"/"negative", or any other pair
with pos_label); imbalanced-learn itself isn't required (fit_resample
is duck-typed, so imblearn.pipeline.Pipeline still works if it's installed
separately). Note that hard positives are not contrast sets or counterfactual edits
(minimal edits of an existing example that flip its label): each one is a new example
whose label stays positive, and "hard" is the LLM's judgment, not verified against a
classifier.
sampling_strategy follows imbalanced-learn's semantics, restricted to generating the
positive class: "auto" (the HardPositiveOverSampler default) generates until
positives match negatives; a float in (0, 1] is the desired positive/negative ratio
after resampling; a dict {pos_label: n} is the desired total number of positives
after resampling; a callable f(y) returning such a dict also works. A strategy that
would require generating negatives raises ValueError. random_state (an int or a
numpy.random.RandomState) seeds exemplar sampling.
TypicalPositiveOverSampler.fit_resample has a different goal: instead of hard
positives for classifier augmentation, it generates typical positive-class texts with
specific identifying details (names, exact dates/numbers, locations, verbatim phrases)
generalized away, as a stand-in you can publish when the original pool can't be shared.
It has no default sampling_strategy, since there's no natural target size for such a
set. The negative pool is still required (for the same binary-label validation as
HardPositiveOverSampler), but it's
never shown to the backend — only positive exemplars inform generation, since contrasting
against negatives would frame generation around the boundary rather than the typical
case. Removing identifying details is best-effort: besides the prompt instructions, a lightweight verbatim-
substring check (min_verbatim_span, default 20 characters) rejects and retries any
generated text that copies a long span straight out of a positive exemplar — this catches
copy-through leaks but not paraphrased ones, so it's not a privacy guarantee. In
particular, it is not differentially private: positive exemplars go into the prompt
verbatim. If you need a formal guarantee, use a DP method that keeps private text out of
the prompt, such as Aug-PE (Xie et al., ICML 2024) or
DP fine-tuning of the generator (Yue et al., ACL 2023).
Renamed in 0.16.0.
OverSampler→HardPositiveOverSampler,SyntheticSampler→TypicalPositiveOverSampler, and theirn_synthesized/seedparameters →sampling_strategy/random_state(imbalanced-learn's names). The old names still work with aDeprecationWarningand will be removed in 0.18.0.n_synthesized=ncorresponds tosampling_strategy={pos_label: n_positive + n};n_synthesized=Noneto"auto".
Installation
pntx uses uv for package management.
uv add pntx # core (scikit-learn + pydantic)
uv add "pntx[llama]" # + llama.cpp in-process backend
uv add "pntx[finetuning]" # + FineTuningClassifier (transformers + torch)
uv add "pntx[embeddings]" # + semantic similarity for selectors
scikit-learn and pydantic are core dependencies (every t2pn classifier's
scikit-learn contract and the pn2t over-samplers' structured LLM output need them
respectively). Each backend/feature otherwise lives behind its own extra, and using
one without installing it raises a clear ImportError with the install command to run.
Backends
pntx runs models via a Backend protocol, shared by LLMPromptingClassifier,
HardPositiveOverSampler, and TypicalPositiveOverSampler. FineTuningClassifier does not use this
abstraction at all -- it has no LLM calls, only a fine-tuned transformers encoder, so
there's no loaded model to share with the others:
LlamaCppBackend(pntx[llama]) — runs a GGUF model in-process viallama-cpp-python. This is the primary, most-tuned backend: classification uses token log-probabilities directly (score_choices), and batched classification reuses the shared few-shot prefix's KV cache across every item instead of re-evaluating it per item.
clf = LLMPromptingClassifier(backend="llama", backend_kwargs={"model_path": "model.gguf"})
# or pass a backend instance directly, e.g. for dependency injection in tests
from pntx.backends.llama import LlamaCppBackend
clf = LLMPromptingClassifier(backend=LlamaCppBackend(model_path="model.gguf"))
A remote API backend can be added later by implementing the Backend protocol
(pntx.backends.base.Backend) and passing an instance directly — no built-in one
ships right now.
backend_kwargs is only used when backend is given as a string; it's a single dict
(rather than **kwargs) so LLMPromptingClassifier and the pn2t over-samplers stay compatible
with scikit-learn's get_params()/clone().
LlamaCppBackend accepts either a local model_path or a repo_id (optionally
narrowed to one file with filename) to pull a GGUF model from the Hugging Face Hub
via Llama.from_pretrained. Any other keyword — n_ctx, n_gpu_layers,
flash_attn, verbose, ... — is forwarded as-is to llama_cpp.Llama:
clf = LLMPromptingClassifier(
backend="llama",
backend_kwargs={
"repo_id": "Qwen/Qwen2.5-1.5B-Instruct-GGUF",
"filename": "*q4_k_m.gguf",
"n_ctx": 4096,
"n_gpu_layers": -1, # offload all layers to GPU
"flash_attn": True,
},
)
To share one loaded model across LLMPromptingClassifier and the pn2t over-samplers
(recommended for local inference — avoids loading the same GGUF twice), construct the
backend once and pass the instance to each:
from pntx.backends.llama import LlamaCppBackend
backend = LlamaCppBackend(model_path="model.gguf")
clf = LLMPromptingClassifier(backend=backend)
sampler = HardPositiveOverSampler(backend=backend)
synth = TypicalPositiveOverSampler(backend=backend, sampling_strategy={1: 100})
Selecting exemplars
When there are more fitted texts (on either side) than comfortably fit in a prompt, a
Selector decides which ones to use — LLMPromptingClassifier calls it independently for the
positive and negative pools:
RandomSelector(default) — a uniform random subset.NearestSelector— picks texts most similar to the text being classified; dynamic, per-query selection.DiversitySelector— greedily picks a maximally diverse subset.BudgetSelector— picks as many texts as fit within a token budget (used internally by thepn2tover-samplers for their exemplar sampling).
NearestSelector and DiversitySelector take a similarity_fn. It defaults to a
dependency-free character n-gram similarity (pntx.dedup.similarity); pass
pntx.embeddings.cosine_similarity_fn() (requires pntx[embeddings]) for semantic
similarity instead:
from pntx.t2pn import LLMPromptingClassifier
from pntx.selection import NearestSelector
clf = LLMPromptingClassifier(
backend="llama", backend_kwargs={"model_path": "model.gguf"}, selector=NearestSelector()
)
LLMPromptingClassifier treats a selector as static or dynamic based on its
query_aware attribute (RandomSelector/DiversitySelector/BudgetSelector are
static; NearestSelector is the only built-in dynamic one):
- Static (default): exemplar selection, ordering, and calibration (see below) are
all resolved once in
fit()and reused by every laterpredict/predict_probacall — this is what lets aBatchScoringBackend(e.g.LlamaCppBackend) evaluate the shared few-shot prefix once per call and reuse its KV cache across the whole batch. - Dynamic (e.g.
NearestSelector): exemplars genuinely relevant to each text can't be known ahead of time, so selection reruns per text insidepredict/predict_probainstead. For aBatchScoringBackendthis forfeits the shared-prefix KV-cache reuse above (each text gets its own prefix and its own backend call), andLLMPromptingClassifierraises aUserWarningonce per call to flag the latency trade-off.
LLMPromptingClassifier also applies content-free calibration (Zhao et al. 2021, "Calibrate
Before Use") by default on the ScoringBackend path: it scores an empty placeholder
query against the same few-shot prefix to estimate the prefix's own label bias (an
artifact of which exemplars ended up in it and in what order — few-shot prompts are
known to be sensitive to this), then divides each real prediction by that baseline and
renormalizes. Pass LLMPromptingClassifier(..., calibrate=False) to disable it and get the raw,
uncalibrated softmax instead.
The pn2t over-samplers don't take a Selector; instead their sample_method
constructor argument picks a budget-based sampling strategy (a full port of semaxis's
own sample_method/embedding_model for HardPositiveOverSampler;
TypicalPositiveOverSampler reuses the same mechanism for its positive-only exemplar
sampling):
"random"(default) — a uniform random subset, filled until the token budget runs out (BudgetSelectorunder the hood)."kmeans"— embeds the pool viaembedding_model(requirespntx[embeddings]) and picks one representative text per K-Means cluster."votek"— embeds the pool and runs the Vote-K algorithm (Su et al. 2022), balancing representativeness and diversity.
sampler = HardPositiveOverSampler(
backend="llama",
backend_kwargs={"model_path": "model.gguf"},
sample_method="votek",
embedding_model="paraphrase-albert-small-v2", # sentence-transformers model name
)
Development
uv sync # install dev dependencies
uv run pytest # unit tests (integration tests are skipped by default)
uv run ruff check .
uv run mypy src tests
Integration tests that hit a real model or API are opt-in:
PNTX_LLAMA_MODEL_PATH=/path/to/model.gguf uv run pytest tests/integration
Metadata
Release files for pntx 0.16.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pntx-0.16.0.tar.gz | 49.9 kB | Without provenance | Details for pntx-0.16.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pntx-0.16.0-py3-none-any.whl | Python 3 | none | any | Details for pntx-0.16.0-py3-none-any.whl |
Total release size: 112.4 kB
Release files / pntx-0.16.0.tar.gz
| Download URL | pntx-0.16.0.tar.gz |
|---|---|
| Size | 49.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8de9a7dec7d110af902344373cbe5cadd1f988e21ec3c18b6b8aa2af6a7d0e06
|
|
BLAKE2b-256 checksum How to use checksums |
2ba2b5ea64f7cab0a1470b634581e369f187379206817e0a8c9b03e5d1c81370
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Release files / pntx-0.16.0-py3-none-any.whl
| Download URL | pntx-0.16.0-py3-none-any.whl |
|---|---|
| Size | 62.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
fcc6fa7b0561af8eee24383dd6c2d5acb72b94f717f414c3329411a14a7b38a3
|
|
BLAKE2b-256 checksum How to use checksums |
0399f902fda094284057af504c364055350a46d380326a0067b520fff8f558eb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Security for pntx 0.16.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.