MacPaw/Gliner2Swift
Acerca de
Swift port of Gliner2 framework
IA y aprendizaje automáticoWhat you can do
- GLiNER2 (span) and GLiNER2.5 (boundary) checkpoints behind one API, with the architecture picked from the checkpoint's config.json
- Named Entity Recognition (NER) — with GLiNER2.5, entities of any length
- Text Classification (with optional prompts, label descriptions, and few-shot examples)
- Structured Data Extraction (JSON schemas, including the name::dtype::[a|b]::desc field-spec form)
Crecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- Recopilando historial
- in 15 days
- Recopilando historial
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalGLiNER2Swift
Swift/MLX implementation of GLiNER2 - a unified schema-based information extraction framework. (Article)
Table of Contents
- Features
- Requirements
- Installation
- Quick Start
- Available Models
- API Reference
- LoRA Adapters
- Architecture
- Performance
- Work in Progress
- Contributing
- Acknowledgments
Features
- GLiNER2 (span) and GLiNER2.5 (boundary) checkpoints behind one API, with the
architecture picked from the checkpoint's
config.json - Named Entity Recognition (NER) — with GLiNER2.5, entities of any length
- Text Classification (with optional prompts, label descriptions, and few-shot examples)
- Structured Data Extraction (JSON schemas, including the
name::dtype::[a|b]::descfield-spec form) - Relation Extraction
- Long-document extraction via automatic chunking, plus
maxLentruncation - Optional int8 encoder quantization (~40% less memory)
- LoRA adapter loading (merge at load time, zero runtime overhead)
- Native Apple Silicon support via MLX (Metal GPU)
Requirements
- macOS 14.0+ or iOS 17.0+
- Swift 5.9+
- Apple Silicon (M1/M2/M3) on macOS; A-series (Metal) on iOS
Installation
Swift Package Manager
Add to your Package.swift:
dependencies: [
.package(url: "https://github.com/MacPaw/Gliner2Swift", branch: "main"),
]
Or in Xcode: File → Add Package Dependencies → Enter the repository URL.
Quick Start
import GLiNER2Swift
// Load model (downloads automatically from HuggingFace, or pass a local directory)
let model = try await GLiNER2.fromPretrained("fastino/gliner2-base-v1")
// Extract entities — results come back as a [String: Any] dictionary
let text = "Tim Cook is CEO of Apple in Cupertino."
let result = model.extractEntities(
text: text,
entityTypes: ["person", "company", "location"],
includeSpans: true
)
if let entities = result["entities"] as? [String: [Any]] {
for (label, spans) in entities {
for case let span as [String: Any] in spans {
print("\(label): \(span["text"]!) [\(span["start"]!)-\(span["end"]!)]")
}
}
}
// person: Tim Cook [0-8]
// company: Apple [23-28]
// location: Cupertino [32-41]
Available Models
| Model | Architecture | Parameters | HuggingFace ID |
|---|---|---|---|
| GLiNER2 base | span | 205M | fastino/gliner2-base-v1 |
| GLiNER2.5 small | boundary | 74M | fastino/gliner2.5-small-v1 |
| GLiNER2.5 base | boundary | 194M | fastino/gliner2.5-base-v1 |
| GLiNER2.5 multilingual | boundary | 287M | fastino/gliner2.5-multi-v1 |
Every row loads straight from its HuggingFace repository (or from a directory produced by
scripts/convert_weights.py, which also writes fp16 and int8 variants). GLiNER2.5 models
decode entities, classifications, JSON structures (legacy single-instance and record mode —
Schema.structure(name, mode: "natural" | "latent" | "anchorless"), which extractJson
uses by default on a 2.5 checkpoint), choice fields and relations with prediction parity
against gliner2 2.0.0 (BoundaryPredictionParityTests, 70 / 69 / 70 cases for small /
base / multi).
API Reference
The extraction methods are synchronous (not throws) and return a [String: Any] result
dictionary; only fromPretrained is async throws.
Entity Extraction
let result = model.extractEntities(
text: "Your text here",
entityTypes: ["person", "organization", "location"]
)
// result["entities"] is [String: [Any]] — label → list of matches
Text Classification
let result = model.classifyText(
text: "Great product, highly recommend!",
task: "sentiment",
labels: ["positive", "negative", "neutral"]
)
// result["sentiment"] == "positive"
Structured Extraction
let schema = model.createSchema()
.entities(["person", "company"])
.classification(task: "sentiment", labels: ["positive", "negative"])
let result = model.extract(text: text, schema: schema)
Long Documents
// Splits into overlapping word-chunks, remaps spans back to the original text, and merges.
let result = model.extractEntitiesLong(text: veryLongText, entityTypes: ["person", "company"])
LoRA Adapters
GLiNER2Swift supports loading LoRA (Low-Rank Adaptation) adapters trained with the Python GLiNER2 framework. Adapters are merged into the base weights at load time, giving identical results to Python with zero runtime overhead.
Loading an Adapter
// One-step: load base model + adapter together
let model = try await GLiNER2.fromPretrained(
"fastino/gliner2-base-v1",
adapterPath: "/path/to/adapter"
)
// Two-step: load base model first, then attach adapter
let model = try await GLiNER2.fromPretrained("fastino/gliner2-base-v1")
try model.loadAdapter(from: "/path/to/adapter")
Adapter Directory Structure
The adapter directory must contain:
adapter_config.json- LoRA configuration (rank, alpha, target modules)adapter_weights.safetensors- LoRA weight matrices
All parameters (rank, alpha, dropout, target modules) are read from adapter_config.json - any valid LoRA configuration is supported.
How It Works
Instead of maintaining separate LoRA modules at runtime, weights are merged at load time:
W_merged = W_base + (lora_B @ lora_A) * (alpha / r)
This produces numerically identical results to Python's model.load_adapter() + model.merge_lora() pipeline.
Architecture
GLiNER2Swift is a direct port of the Python GLiNER2 implementation, achieving numerical parity with the reference implementation:
- Encoder: DeBERTa v3 with disentangled attention (shared by both architectures)
- GLiNER2 (span):
- Span Marker: MLP-based span representation
- Count LSTM: For predicting entity counts
- Downscaled Transformer: For schema embedding
- GLiNER2.5 (boundary,
Sources/GLiNER2Swift/Model/Boundary/):- Boundary encoder: one state per word boundary, windowed self-attention + SwiGLU
- Query head: start / end / inside marginals per query
- Shared candidate pool: 192 document-level spans, selected with exact integer sort keys so the pool matches PyTorch's stable sorts
- Pool scorer: FiLM-conditioned reranker with span content and inside evidence, plus a per-query abstention logit
- Relation scorer: typed, capped head × tail pairs over the entity candidates
- Record head: natural / latent / anchorless instance formation with null-aware field assignment (Hungarian assignment for exclusive scalar fields)
Performance
On Apple Silicon (M3 Pro), Release build, fp16, p50 over 100 runs
(PerfBenchmarkTests; details and history in benchmarks/BASELINE.md):
| model | single sentence | ~450-word document | 32-text batch | active memory |
|---|---|---|---|---|
| gliner2-base-v1 | 12.7 ms | 32.7 ms | 116 ms | 417 MB |
| gliner2.5-small-v1 | 5.2 ms | 10.8 ms | 21 ms | 149 MB |
| gliner2.5-small-v1, int8 encoder | 4.0 ms | 10.1 ms | 19 ms | 87 MB |
| gliner2.5-base-v1 | 10.5 ms | 24.0 ms | 45 ms | 377 MB |
| gliner2.5-base-v1, int8 encoder | 7.3 ms | 22.8 ms | 43 ms | 215 MB |
| gliner2.5-multi-v1 | 10.8 ms | 33.0 ms | 57 ms | 557 MB |
Loading a model and running the first extraction takes about 0.1–0.2 s.
Measure in Release: a Debug build of this package (and of mlx-swift) roughly doubles the
per-call latency, because building the lazy graph is Swift code. compileEncoder is not a
speed-up in Release builds — leave it off unless you have measured otherwise.
Opt-in int8 encoder quantization cuts steady-state memory by about 40 % for a small
accuracy trade-off; pass quantization: .int8 to fromPretrained, or load a directory
converted with scripts/convert_weights.py --quantize int8.
GLiNER2.5 is faster than GLiNER2 at every size, and by 2.5× on batches, because the boundary head replaces the span grid and its per-schema readbacks.
Work in Progress
This is an active port of the Python GLiNER2 implementation. Inference is at full prediction parity with the reference. The following are not yet implemented:
- Training loop - Fine-tuning and training from scratch are not yet supported
- PyTorch
.bincheckpoints - Only safetensors weights are loadable (MLX cannot read pickle) - GLiNER2.5 extras - entity attributes (
AttributeGroup), the constrainedClassifierand theJointIEfacade are not ported (pure post-processing over the same heads) - GLiNER2 v1 variants -
gliner2-large-v1andgliner2-multi-v1need thecount_lstmcounting layer, which is not wired on the span path yet (the encoder shape is read fromencoder_config/config.jsonalready)
Contributions and PRs are welcome!
Contributing
See CONTRIBUTING.md for guidelines on submitting PRs, branch naming conventions, and parity testing requirements.
Acknowledgments
Explorar proyectos relacionados
Cargando…