/ Модель

Характеристики

Лицензия
Apache 2.0
Базовая модель
gliner-relex-base-v1.0
Библиотека
gliner
Опубликована
20 ноя 2026

gliner-neuro-symbolic-extractor

Разметка токеновТекст → label4 профессии

Открытая модель GLiNER для однопроходного извлечения сущностей и отношений из английского текста с формированием структурированных данных.

0скачиваний за 30 дней5лайковвеса обновлены28 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

ypipe/gliner-neuro-symbolic-extractor — открытая исследовательская модель, опубликованная iunera для извлечения структурированных фактов из текста в составе нейросимволической системы Y̊pipe и для прототипирования. Она основана на архитектуре GLiNER с backbone DeBERTa-v3 и объединяет распознавание именованных сущностей и извлечение направленных отношений за один проход. Варианты base и large содержат примерно 225 млн и 459 млн параметров; доступны веса PyTorch, ONNX FP32 и INT8 ONNX. Репозиторий ориентирован на быстрый инференс на CPU и Edge NPU, в том числе из Python и Java 17+.

Модель извлекает типизированные фрагменты сущностей, символьные смещения, числовые значения с единицами измерения и отношения по заданным меткам. Среди описанных сценариев — преобразование текста в структуры Schema.org и графы JSON-LD, а также извлечение клинических значений и отношений для структурированных записей. Основной язык обучения и проверки — английский; качество на немецком и других языках не подтверждено.

Автор характеризует модель как исследовательский прототип и подтверждение концепции. Приведённые в карточке результаты основаны на небольших предварительных тестах; генеративные модели могут лучше извлекать широкий набор фактов, а клиническое применение не сертифицировано. Лицензия — Apache-2.0.

Сценарии применения

  • извлечение сущностей и отношений из английского текста
  • преобразование описаний товаров и организаций в Schema.org или JSON-LD
  • выделение лекарств, дозировок, частоты приёма и медицинских показателей из текста
  • извлечение числовых значений и единиц измерения из документов
  • обработка текстовых потоков на CPU или Edge NPU

Ограничения

Это исследовательский прототип с предварительными оценками на небольших тестах; качество на немецком и других языках не проверено. Модель не является сертифицированным медицинским устройством или самостоятельным средством клинической диагностики.

Для каких профессий подходит4

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

🧠🔗 GLiNER Y̊pipe Neuro-Symbolic AI Symbol Extractor (base & large) — Research Prototype for Single-Pass CPU/NPU INT8 Entity, Relation & Schema.org JSON-LD Extraction

⚠️ Research Prototype & Proof of Concept Notice

  • Research Prototype - no warranties - use at your own risk: This repository is an open-weights Research Prototype & Proof of Concept published by iunera to demonstrate how compact, single-pass INT8 encoder models power high-speed symbol extraction for neuro-symbolic AI on everyday CPUs, Edge NPUs, and JVM Big-Data streams. ypipe/gliner-neuro-symbolic-extractor is an open-vocabulary, single-pass joint Named Entity Recognition (NER) and Relation Extraction (RelEx). Originally it is used in the full neurosymbolic AI Y̊pipe in its Manifold engine. This fine tuned GLiNER Schema.org extraction model is provided for neurosymbolic research, architectural evaluation, and prototyping — it is not a certified medical device or standalone clinical diagnostic product.

Gratefully built upon Knowledgator's pioneering GLiNER-RelEx checkpoints and the foundational GLiNER architecture (DeBERTa-v3), both variants (base ~225M and large ~459M) extract typed entity spans, exact character offsets, numeric units, and directional relationships simultaneously in one single forward pass—including Schema.org / W3C JSON-LD graphs and structured clinical patient-file values. Both folders ship with PyTorch weights, FP32 ONNX, and CPU/NPU-friendly INT8 Quantized ONNX graphs ready for zero-PyTorch execution in Python and in-process Java 17+.

⚡ Key Research Findings at a Glance (Quick Navigation)


🧬 What This Research Prototype Was Trained On — And Why It Transfers Across Domains

To test whether a compact (283 MB INT8) single-pass encoder can replace slow generative LLMs for structured grounding, we fine-tuned knowledgator/gliner-relex-base-v1.0 and knowledgator/gliner-relex-large-v1.0 jointly across diverse schematic domains:

  1. Broad Schema.org Vocabulary Classes & Relational Properties: Trained across core Schema.org types (Person, Organization, Product, SoftwareApplication, Place, Event, MonetaryAmount, Drug, MedicalCondition, etc.) and relational properties (founder, worksFor, location, manufacturer, price, author, memberOf, contraindication) so unstructured web, enterprise, and catalog prose maps directly into linked data.
  2. Quantitative Units, Dosages & Clinical Patient-File Relations: Trained on medications, dosages, administration frequencies, conditions/indications, lab biomarkers (eGFR, INR, HbA1c, potassium), numeric measurements with units (mg, mcg, mL/min, mmol/L, EUR, USD), and directional relations (treats, has_dosage, has_frequency, has_value, contraindicated_with).
  3. Technical, Software & Operational Entities: Trained on system components, parameters, states, and structured attribute-value pairs common in engineering and enterprise logs.
  4. Hard-Negative & Interrogative Calibration: Included uninstantiated mentions and questions (e.g., "Which medication treats hypertension?") so the model learns to distinguish asserted factual spans from generic query terms.

Why This Demonstrates Feasibility for Any Specialized Vertical

Because GLiNER-RelEx dynamically embeds target entity and relation labels directly inside the input prompt (<<ENT>> ... <<REL>> ...) during its single bidirectional pass, domain adaptation does not require 70B+ LLMs or brittle JSON prompt engineering. That a single 283 MB–655 MB INT8 prototype handles Schema.org graphs, clinical dosages, and technical parameters in 22–55 ms on a laptop CPU proves that the exact same neuro-symbolic recipe is immediately feasible for other specialized areas—such as financial KYC & regulatory filings, customs & logistics bills of lading, industrial IoT maintenance logs, insurance claims, and legal contract auditing.


📊 Study 1 (Preliminary Assessment): Schema.org JSON-LD Extraction — Neuro-Symbolic CPU INT8 vs. Compact llama.cpp LLMs

Why spend seconds of generative LLM compute per paragraph just to turn unstructured text into Schema.org (https://schema.org/docs/schemas.html) entities and properties?

As a preliminary micro-benchmark assessment (N = 8 multi-entity enterprise, technical, and clinical passages) (benchmarks/schema_org_benchmark.py, raw output in benchmarks/schema_org_benchmark_results.json), we evaluated single-pass extraction of official Schema.org classes (Person, Organization, Product, SoftwareApplication, Place, Event, MonetaryAmount, Drug, MedicalCondition) and properties (founder, worksFor, location, manufacturer, price, author, memberOf, contraindication) into valid W3C JSON-LD 1.1 on one laptop CPU (AMD Ryzen 5 PRO 7540U Zen 4, 6C/12T, zero GPU) against upstream Knowledgator GLiNER-RelEx checkpoints and compact native C++ llama.cpp models (llama-server build b11541, Zen 4 AVX-512, JSON mode, warm session, --reasoning-budget 0):

Preliminary Assessment: Schema.org JSON-LD Extraction — Neuro-Symbolic INT8 ONNX vs. Knowledgator Upstream & Native C++ llama.cpp LLMs

Model / Extraction Engine (N = 8 Micro-Benchmark)RuntimeMean Latency / Doc10,000 Docs (1 CPU)Speedup vs. llama.cpp 2BSchema.org Entity F1Schema.org Relation F1Hallucinated Values
ypipe/gliner-neuro-symbolic (base INT8)ONNX Runtime CPU22.0 ms3.7 min ($0)398x faster98.3%74.4%0 (substring)
ypipe/gliner-neuro-symbolic (large INT8)ONNX Runtime CPU54.7 ms9.1 min ($0)160x faster98.2%82.1%0 (substring)
knowledgator/gliner-relex-base-v1.0PyTorch FP32 CPU118.9 ms19.8 min74x faster96.7%74.5%0 (substring)
knowledgator/gliner-relex-multi-v1.0PyTorch FP32 CPU117.7 ms19.6 min74x faster96.7%75.0%0 (substring)
Qwen3.5-0.8B (IQ4_XS GGUF, JSON mode)Native C++ llama.cpp3,209.7 ms8.9 hrs2.7x77.8%41.0%2 invented
Qwen3.5-2B (IQ4_XS GGUF, JSON mode)Native C++ llama.cpp8,745.7 ms24.3 hrs1.0x (baseline)84.6%77.8%0
Larger Local / Frontier Cloud LLMs (7B–70B+ JSON Mode)GPU / External Cloud~1.5–15+ s~4–40+ hrs + GPU/API costGPU / Cloud-bound~96–99% (Clearly higher)~85–95% (Clearly higher)Rare (no char offsets)

📌 Preliminary Scope & Larger-LLM Scaling Note: This is an initial N = 8 micro-benchmark comparing models small enough to run purely on a laptop CPU (0.2B–2B). Larger LLMs (7B–70B+ local GPU models and frontier cloud APIs) are clearly stronger on open-ended zero-shot recall, implicit phrasing, and complex relational reasoning—at the trade-off of 100x–1,000x+ higher compute cost, GPU/cloud hardware requirements, and external data exposure when calling cloud APIs.


🧪 Study 2 (Preliminary Assessment): Dosage & Numeric Fidelity — Substring Slicing vs. Generative LLM Token Synthesis

In medicine, pharmacology, and finance, re-typing numbers and units token-by-token carries a structural synthesis risk. An autoregressive LLM generating {"text": "..."} JSON has no character-index pointer back to the source string—it re-generates every digit, unit, and word from scratch. By contrast, gliner-neuro-symbolic-extractor predicts (startChar, endChar) boundary indices and slices source_text[startChar:endChar] directly, guaranteeing 100% verbatim substring fidelity by construction.

As a preliminary assessment (N = 20 clinical dosage, decimal, mcg/mg, renal biomarker, and financial price sentences), we tested this invariant against compact CPU llama.cpp models (benchmarks/dosage_and_numeric_mutation_benchmark.py, raw JSON in benchmarks/dosage_and_numeric_mutation_results.json):

Preliminary Assessment: Dosage & Numeric Fidelity — Substring Slicing vs. LLM Token Synthesis

Model / Engine (N = 20 Preliminary Assessment)RuntimeMean LatencyExtracted SpansNon-Verbatim Spans (Exact Substring Check)Gold Numeric Recall
ypipe/gliner-neuro-symbolic (base INT8)ONNX Runtime CPU21.8 ms840 (100% Verbatim Slice)91.7%
ypipe/gliner-neuro-symbolic (large INT8)ONNX Runtime CPU69.2 ms790 (100% Verbatim Slice)86.1%
Qwen3.5-0.8B (IQ4_XS GGUF, JSON mode)Native C++ llama.cpp1,856.0 ms907 non-verbatim ('Dosage', 'Orally', re-cased strings)63.9%
Qwen3.5-2B (IQ4_XS GGUF, JSON mode)Native C++ llama.cpp6,134.0 ms1070 (282x slower than base INT8)97.2%
  • Observed Drift in Ultra-Compact 0.8B LLMs: Under strict exact-substring checking (span in source_text), llama.cpp Qwen3.5-0.8B emitted 7 non-verbatim strings across the 20 sentences—including inventing the meta-label 'Dosage' as an entity value, misclassifying and re-casing 'Orally' as a numeric measurement, and re-casing 'Serum creatinine' / 'Serum Potassium'—while recalling 63.9% of target numbers in 1.86 s/doc.
  • Larger LLMs Are Clearly Better on Recall (The Engineering Trade-Off): Notice that scaling up just to Qwen3.5-2B already lifted numeric recall to 97.2% with 0 non-verbatim spans on this 20-case sample—and larger 7B–70B+ LLMs are clearly stronger still on zero-shot coverage and instruction adherence. The neuro-symbolic argument is not that a 283 MB prototype beats larger LLMs on raw recall, but that achieving 97.2% with 2B already required 6.13 seconds per sentence (282x slower than base INT8's 21.8 ms) and still produced generative text strings without guaranteed [startChar..endChar] source offsets. In a neuro-symbolic pipeline, the 22 ms extractive encoder provides instant, offset-locked local perception on CPU/NPU, reserving heavier models or symbolic verification only where needed.

⚙️ Study 3: Pure Computational Scaling (O(1) vs. O(N_out)) & Edge NPU Hardware Fit

Why is there a 2-orders-of-magnitude (146x–398x) compute gap between gliner-neuro-symbolic-extractor and compact GGUF LLMs running on the exact same CPU? It comes down to pure computational complexity:

  • Single-Pass Bidirectional Encoder (O(1) Forward Passes per Document): Regardless of whether a paragraph contains 2 entities or 15 entities and 10 relations, gliner-neuro-symbolic-extractor executes exactly 1 parallel encoder forward pass (0 autoregressive decode steps and 0 KV-cache growth). Across 100,000 documents, it performs 100,000 forward passes total (36.7 CPU-minutes for base INT8; 6.1 CPU-hours for 1,000,000 documents).
  • Autoregressive Generative LLM (O(N_out) Sequential Passes per Document): Emitting structured JSON for entities and relations requires ~115–150 output tokens per document. Every single token forces a serial forward pass over the model weights + KV-cache—turning 100,000 documents into ~11.5M to ~13.5M sequential passes (89.2 CPU-hours for 0.8B and 242.9 CPU-hours / 10.1 CPU-days for 2B, or 101.2 CPU-days per million documents).

Computational Scaling Study: Single-Pass O(1) Encoder vs. O(N) LLM Decode

🚀 Why Single-Pass INT8 Encoder Graphs Excel Even Further on Edge NPUs

If you deploy on modern AI PCs, edge gateways, or clinical tablets equipped with dedicated Neural Processing Units (NPUs)—such as AMD Ryzen AI (XDNA / XDNA 2), Intel Core Ultra (AI Boost / OpenVINO NPU), Apple Silicon Neural Engine (ANE), or Qualcomm Hexagon NPU—this architectural advantage widens even further:

  1. Compute-Bound Dense INT8 MatMul vs. Memory-Bandwidth-Bound batch=1 LLM Decode: Autoregressive LLM token generation (batch=1) is severely bottlenecked by LPDDR5 memory bandwidth because the chip must fetch model weights + growing KV-cache from system RAM for every generated token, leaving systolic NPU matrix engines idle most of the time. By contrast, a single-pass bidirectional encoder processes all prompt labels + document tokens simultaneously in one dense [seq_len, hidden_dim] INT8 matrix-multiply pass, maximizing arithmetic intensity (MACs per byte) inside fast NPU SRAM tiles.
  2. Zero Dynamic KV-Cache & Static Operator Topology: Edge NPUs are purpose-built for fixed-operator INT8 tensor graphs (MatMul, Gemm, LayerNorm) without dynamic KV-cache allocation, autoregressive control loops, or stateful JSON grammar samplers.
  3. Standard ONNX Runtime NPU Offload (283 MB Footprint): Because models/base/onnx/model_quantized.onnx is just 283 MB in standard ONNX (opset 17), compiling fixed sequence buckets (e.g., 128 / 256 / 512 tokens) targets ONNX Runtime hardware providers (VitisAIExecutionProvider, OpenVINOExecutionProvider, CoreMLExecutionProvider, QNNExecutionProvider), freeing 100% of host CPU cores for application logic or local databases. (All benchmark tables in this repository report pure CPU baselines with zero NPU/GPU acceleration.)

🏗️ Study 4: Enterprise Java & Big-Data Streaming Architecture — In-Process Pure JVM ONNX vs. Python Sidecar Sprawl

In Big Data and enterprise streaming architectures—such as Apache Kafka, Apache Flink, Apache Spark, Apache Druid, ClickHouse ingestion pipelines, and HAPI HL7 FHIR hospital routers—most NLP deployments suffer from the Python Microservice Sidecar Anti-Pattern: every JVM worker must serialize records to JSON, hop over localhost/pod TCP sockets to a Python FastAPI/PyTorch container (bound by Python's GIL and multi-gigabyte PyTorch RAM), and parse JSON responses back into JVM objects on every single event.

Because ypipe/gliner-neuro-symbolic-extractor runs natively in pure Java 17+ (GlinerOnnxExtractor.java) with only 3 Maven dependencies (com.microsoft.onnxruntime:onnxruntime, ai.djl.huggingface:tokenizers, Jackson), you embed the 283 MB INT8 OrtSession directly inside your JVM stream worker with zero IPC and zero Python infrastructure.

We benchmarked both architectures head-to-head on the same AMD Ryzen 5 PRO 7540U laptop CPU (benchmarks/jvm_bigdata_sidecar_benchmark.py + Main.java --benchmark, raw metrics in benchmarks/jvm_bigdata_benchmark_results.json):

Big-Data JVM Architecture: Python Sidecars vs. In-Process ONNX

Big-Data Deployment Architecture (base Model)IPC / Network OverheadWorker Process RSS MemorySingle-Record Latency (Median / p95)Node Stream Throughput (docs/sec)Node Stream Throughput (docs/hour)
In-Process Java 17+ (GlinerOnnxExtractor, 3-Thread Shared OrtSession)Zero IPC (In-Memory)935 MB (entire JVM)— (parallel stream)41.1 docs/s148,085 docs/hr (5.8x)
In-Process Java 17+ (GlinerOnnxExtractor, Single-Thread)Zero IPC (In-Memory)935 MB (entire JVM)30.9 ms / 32.1 ms32.5 docs/s116,917 docs/hr (4.6x)
Python PyTorch + HTTP JSON Microservice Sidecar (FP32)JSON -> TCP/HTTP -> GIL -> JSON2,638 MB (+ JVM client)141.1 ms / 152.5 ms7.0 docs/s25,335 docs/hr (1.0x)
  • Why This Matters at 10M+ Record Big-Data Scale: A single thread-safe OrtSession inside a Kafka Streams, Flink, or Spark executor processes 148,085 documents per hour per laptop-class CPU while cutting per-worker memory by 2.8x (935 MB vs. 2,638 MB)—allowing Kubernetes and bare-metal clusters to pack nearly 3x more stream workers per node with zero Python container lifecycle, pip/CUDA drift, or HTTP timeout cascades.

🏥 Vision: Low-Compute, Private Patient-to-Study Matching Across Millions of Medical Studies

Across hospitals, rural clinics, and research institutions—especially in lesser-developed and resource-constrained countries—vital clinical observations (diagnoses, prescribed medications, dosages, frequencies, and renal or metabolic biomarkers like eGFR or HbA1c) sit locked inside unstructured patient files.

Using giant cloud LLMs to screen patient charts against global medical literature fails on three fundamental barriers:

  1. Strict Non-Sharing of Medical Data & Patient Sovereignty: Confidential patient records cannot be uploaded across borders to external cloud APIs without violating patient secrecy and healthcare data-protection mandates.
  2. Low Compute & Offline Infrastructure Realities: Regional hospitals and clinics in developing regions rarely have $30,000 datacenter GPUs, per-token cloud budgets, or guaranteed high-bandwidth internet—and asking a generative LLM to re-read millions of medical studies per patient is computationally impossible.
  3. Patient Safety Risks From Generative Hallucination: Next-token predictors can silently alter numeric dosages or invert complex 'NOT / UNLESS' clinical exclusion criteria.

Vision: Private, Low-Compute Patient-to-Study Matching Worldwide — Schematic Patient File Extraction + Schematic Studies Extraction -> Symbolic Matching & Clinical Safety Validation

How Neuro-Symbolic Schematic Extraction + Symbolic Validation Solves This

Our research vision separates neural schematic extraction from symbolic matching and validation so any clinic laptop or low-cost CPU ($300–$500 hardware, 283 MB INT8 footprint, 100% offline) can support evidence-based medicine research:

  1. Stage 1A — Local Schematic Patient File Extraction (~30 ms on Clinic CPU, Zero Data Sharing): On-premise inside the clinic, gliner-neuro-symbolic-extractor extracts verbatim-grounded clinical entities, lab measurements, units, and directional relations directly from the patient file—without a single byte of medical data ever leaving the building.
  2. Stage 1B — Pre-Compiled Schematic Extraction Across Millions of Medical Studies: Global medical studies, clinical trial registries, and dosing guidelines are extracted once into compact, structured eligibility and contraindication criteria—small enough to distribute offline on a local disk or USB drive to any hospital worldwide.
  3. Stage 2 & 3 — Deterministic Symbolic Matching & Safety Validation (< 10 ms CPU): A lightweight local symbolic engine matches the extracted patient profile against millions of pre-structured studies and safety rules in milliseconds—flagging contraindicated medications (e.g., blocking Metformin when eGFR < 30 mL/min), verifying inclusion/exclusion logic without guesswork, and presenting clinicians with transparent source character offsets and auditable rule traces.

📦 Model Variants & Repository Layout (models/base/ vs models/large/)

Both models/base/ (small/fast) and models/large/ (high-F1) are packaged inside models/ as clean, self-contained directories containing zero-pickle model.safetensors, tokenizer assets, and a dedicated onnx/ subfolder (onnx/model.onnx + onnx/model_quantized.onnx):

Variant FolderUpstream Base CheckpointSpan ModeParametersSafetensors (model.safetensors)FP32 ONNX (onnx/model.onnx)INT8 ONNX (onnx/model_quantized.onnx)Recommended Workload
models/base/knowledgator/gliner-relex-base-v1.0 (deberta-v3-base)token_level (BIO)~225M859 MB861 MB283 MBSub-35 ms real-time CPU/NPU perception, Big-Data JVM streams, high-volume Schema.org JSON-LD indexing
models/large/knowledgator/gliner-relex-large-v1.0 (deberta-v3-large)markerV0 (Span)~459M1.78 GB1.78 GB655 MBHighest relational recall (82.1% Schema.org Rel F1) on dense clinical and enterprise sentences (~55–100 ms CPU)
├── models/
│   ├── base/                                    # Small / Fast (~225M, DeBERTa-v3-base, token_level)
│   │   ├── model.safetensors                    # PyTorch weights in zero-pickle Safetensors (859 MB)
│   │   ├── gliner_config.json                   # GLiNER-RelEx configuration
│   │   ├── tokenizer.json                       # Fast HuggingFace Rust/JNI tokenizer
│   │   ├── tokenizer_config.json                # Tokenizer metadata
│   │   ├── spm.model                            # SentencePiece model
│   │   ├── added_tokens.json                    # <<ENT>> (128001), <<SEP>> (128002), <<REL>> (128003)
│   │   ├── special_tokens_map.json              # Special token definitions
│   │   └── onnx/                                # Standard ONNX subfolder inside models/base/
│   │       ├── model.onnx                       # Full-precision dynamic ONNX graph (861 MB, opset 17)
│   │       └── model_quantized.onnx             # CPU/NPU INT8 quantized ONNX graph (283 MB)
│   └── large/                                   # Large / High-F1 (~459M, DeBERTa-v3-large, markerV0)
│       ├── model.safetensors                    # PyTorch weights in zero-pickle Safetensors (1.78 GB)
│       ├── gliner_config.json
│       ├── tokenizer.json
│       ├── tokenizer_config.json
│       ├── spm.model
│       ├── added_tokens.json
│       ├── special_tokens_map.json
│       └── onnx/                                # Standard ONNX subfolder inside models/large/
│           ├── model.onnx                       # Full-precision dynamic ONNX graph (1.78 GB, opset 17)
│           └── model_quantized.onnx             # CPU/NPU INT8 quantized ONNX graph (655 MB)
├── assets/
│   ├── schema_org_benchmark.png                 # Study 1 (Preliminary): Schema.org INT8 vs. llama.cpp
│   ├── dosage_numeric_mutation_study.png        # Study 2 (Preliminary): Verbatim slicing vs. LLM synthesis
│   ├── computation_scaling_study.png            # Study 3: Pure O(1) vs. O(N_out) compute scaling & NPU fit
│   ├── enterprise_jvm_bigdata_architecture.png  # Study 4: In-process JVM ONNX vs. Python HTTP sidecars
│   └── clinical_study_matching_vision.png       # Global clinical study matching & safety validation vision
├── benchmarks/
│   ├── schema_org_benchmark.py                  # Study 1 benchmark suite (ONNX INT8 vs. upstream vs. llama.cpp)
│   ├── schema_org_benchmark_results.json        # Study 1 raw measured timings & F1 scores
│   ├── dosage_and_numeric_mutation_benchmark.py # Study 2 20-case clinical dosage & price fidelity stress test
│   ├── dosage_and_numeric_mutation_results.json # Study 2 raw verbatim & numeric recall metrics
│   ├── jvm_bigdata_sidecar_benchmark.py         # Study 4 Python PyTorch HTTP sidecar RSS & throughput harness
│   └── jvm_bigdata_benchmark_results.json       # Study 4 paired JVM in-process vs. Python sidecar results
└── examples/
    ├── python/                                  # PyTorch (Safetensors) & zero-PyTorch INT8 ONNX examples
    └── java/                                    # Standalone Maven Java 17+ INT8 ONNX single-pass project

🎮 Try It Live in Your Browser — Free Hugging Face Demo Space

Want to test your own clinical summary or business paragraph before installing anything? Open our live interactive Space—https://huggingface.co/spaces/ypipe/gliner-neuro-symbolic-space—and switch between models/base (283 MB INT8 ONNX) and models/large (655 MB INT8 ONNX) directly in the browser:

  • Tab 1 — Single-Pass Patient File Clinical Extraction (models/base/onnx/model_quantized.onnx):

Live Hugging Face Space Demo (Tab 1): Single-Pass Patient File Clinical Extraction

Live Hugging Face Space Demo (Tab 2): Single-Pass Schema.org JSON-LD Extraction


🚀 Single-Pass Usage Guides (Python & Standalone Java)

All runnable scripts are in examples/python/ and examples/java/. Every example executes one single forward pass to extract entities and relations simultaneously.

1. Python — PyTorch (gliner)

pip install -U gliner huggingface_hub
from pathlib import Path
from huggingface_hub import snapshot_download
from gliner import GLiNER

repo_dir = Path(snapshot_download(
    repo_id="ypipe/gliner-neuro-symbolic-extractor",
    allow_patterns=["models/large/*"],
    ignore_patterns=["models/*/onnx/*"],
))
model = GLiNER.from_pretrained(str(repo_dir / "models" / "large"))

text = (
    "Patient File Summary: 64-year-old patient with type 2 diabetes prescribed Metformin 500 mg "
    "twice daily; therapy is contraindicated in severe renal failure after serum eGFR dropped to 28 mL/min."
)

entities, relations = model.inference(
    texts=[text],
    labels=["medication", "dosage", "frequency", "condition", "biomarker", "measurement"],
    relations=["has_dosage", "has_frequency", "treats", "contraindicated_with", "has_value"],
    threshold=0.40,
    relation_threshold=0.45,
    return_relations=True,
    flat_ner=True,
)

for e in entities[0]:
    print(f"[{e['label']:<12}] {e['text']} (chars {e['start']}..{e['end']}, score={e['score']:.3f})")
for r in relations[0]:
    print(f"{r['head']['text']} --[{r['relation']}]--> {r['tail']['text']} (score={r['score']:.3f})")

2. Python — Pure CPU INT8 ONNX Runtime (Zero PyTorch Required)

Run examples/python/extract_onnx.py using only onnxruntime, tokenizers, and numpy:

pip install onnxruntime tokenizers numpy huggingface_hub
python examples/python/extract_onnx.py --model ./models/base --benchmark
import json
from pathlib import Path
from examples.python.extract_onnx import GlinerOnnxExtractor, to_schema_org_jsonld

extractor = GlinerOnnxExtractor(Path("./models/base"), onnx_filename="onnx/model_quantized.onnx")

text = (
    "Dr. Lena Hoffmann founded Helios MedTech GmbH in Munich, Germany, where the company "
    "manufactures the CardioSense Pro monitor priced at 2490 EUR for the European Cardiology Summit."
)

entities, relations = extractor.extract(
    text=text,
    entity_labels=["Person", "Organization", "Product", "Place", "Event", "MonetaryAmount"],
    relation_labels=["founder", "worksFor", "location", "manufacturer", "price"],
    entity_threshold=0.40,
    relation_threshold=0.45,
)

print(json.dumps(to_schema_org_jsonld(entities, relations), indent=2))

Verified Single-Pass Schema.org JSON-LD Output (models/base/onnx/model_quantized.onnx):

{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@id": "urn:entity:person:dr-lena-hoffmann",
      "@type": "Person",
      "name": "Dr. Lena Hoffmann"
    },
    {
      "@id": "urn:entity:organization:helios-medtech-gmbh",
      "@type": "Organization",
      "name": "Helios MedTech GmbH",
      "founder": {
        "@id": "urn:entity:person:dr-lena-hoffmann"
      },
      "location": {
        "@id": "urn:entity:place:munich-germany"
      }
    },
    {
      "@id": "urn:entity:place:munich-germany",
      "@type": "Place",
      "name": "Munich, Germany"
    },
    {
      "@id": "urn:entity:product:cardiosense-pro",
      "@type": "Product",
      "name": "CardioSense Pro",
      "price": {
        "@id": "urn:entity:monetaryamount:2490-eur"
      }
    },
    {
      "@id": "urn:entity:monetaryamount:2490-eur",
      "@type": "MonetaryAmount",
      "name": "2490 EUR",
      "value": 2490.0,
      "currency": "EUR"
    },
    {
      "@id": "urn:entity:event:european-cardiology-summit",
      "@type": "Event",
      "name": "European Cardiology Summit"
    }
  ]
}

3. Standalone Java 17+ — Pure CPU INT8 ONNX Runtime (Zero Spring / Zero Python)

examples/java/ is a self-contained Maven project depending only on com.microsoft.onnxruntime:onnxruntime, ai.djl.huggingface:tokenizers, and Jackson:

cd examples/java
mvn compile exec:java -Dexec.args="--model ../../models/base --benchmark"
mvn exec:java -Dexec.args="--model ../../models/large --benchmark"

Verified Single-Pass Patient File Output (models/large/onnx/model_quantized.onnx in Java):

Input Text:
  Patient File Summary: 64-year-old patient with type 2 diabetes prescribed Metformin 500 mg twice daily; therapy is contraindicated in severe renal failure after serum eGFR dropped to 28 mL/min.

Extracted Entities (6):
  - [condition   ] 'type 2 diabetes' (chars 47..62, score=0.993)
  - [medication  ] 'Metformin' (chars 74..83, score=1.000)
  - [dosage      ] '500 mg' (chars 84..90, score=0.795)
  - [frequency   ] 'twice daily' (chars 91..102, score=1.000)
  - [condition   ] 'severe renal failure' (chars 134..154, score=1.000)
  - [measurement ] '28 mL/min' (chars 183..192, score=0.881)

Extracted Clinical Relations (4):
  - Metformin --[treats]--> type 2 diabetes (score=0.775)
  - Metformin --[has_dosage]--> 500 mg (score=0.985)
  - Metformin --[has_frequency]--> twice daily (score=0.999)
  - Metformin --[contraindicated_with]--> severe renal failure (score=0.853)

⚡ Measured Local CPU Latency (AMD Ryzen 5 PRO 7540U, 6C/12T, Zero GPU)

3 warmup passes + 20 timed single-pass runs on multi-clause clinical & Schema.org sentences:

RuntimeModel ArtifactSize on DiskCold Session LoadPatient File Single-Pass (Median / Mean)Schema.org JSON-LD Single-Pass (Median / Mean)
Java 17+ (onnxruntime 1.30.0)models/base/onnx/model_quantized.onnx283 MB1,648–1,778 ms29.9–34.1 ms / 30.1–34.4 ms28.4–30.9 ms / 28.6–30.8 ms
Python (onnxruntime 1.29.0)models/base/onnx/model_quantized.onnx283 MB1,181 ms37.4 ms / 37.0 ms36.5 ms / 36.0 ms
Java 17+ (onnxruntime 1.30.0)models/large/onnx/model_quantized.onnx655 MB3,428 ms99.8 ms / 107.9 ms88.2 ms / 92.1 ms
Python (onnxruntime 1.29.0)models/large/onnx/model_quantized.onnx655 MB2,724 ms100.5 ms / 98.7 ms97.9 ms / 98.6 ms

🔁 Reproduce Every Study Locally on Your Own CPU

# Study 1: Schema.org JSON-LD extraction (INT8 ONNX vs. upstream PyTorch & optional llama.cpp server)
python benchmarks/schema_org_benchmark.py --output-json benchmarks/schema_org_benchmark_results.json

# Study 2: 20-case clinical dosage, decimal & price verbatim fidelity stress test
python benchmarks/dosage_and_numeric_mutation_benchmark.py --output-json benchmarks/dosage_and_numeric_mutation_results.json

# Study 4: Python PyTorch HTTP sidecar RSS & throughput vs. In-Process Pure Java 17+ ONNX INT8
python benchmarks/jvm_bigdata_sidecar_benchmark.py
mvn -f examples/java/pom.xml compile exec:java -Dexec.args="--model ../../models/base --benchmark"

🔬 Research Prototype Scope & Known Limitations

  • Research Prototype Status (Not a Medical Device): Published strictly as an open-weights research prototype and architectural proof of concept. Do not use for autonomous clinical diagnosis, prescribing, or treatment decisions without qualified human clinical oversight and validated regulatory workflows.
  • Preliminary Micro-Benchmark Sample Sizes (N = 8 & N = 20) & Larger-LLM Comparison: Studies 1 and 2 are preliminary engineering micro-benchmarks designed to measure local CPU latency, architecture, and exact-offset invariants against other laptop-CPU-class models (0.2B–2B)—not large-scale multi-thousand-document clinical evaluations. Larger LLMs (7B–70B+ local GPU models and frontier cloud APIs) are clearly stronger on zero-shot recall, implicit relations, and complex phrasing, at the trade-off of 100x–1,000x+ higher compute cost and lack of intrinsic [startChar..endChar] pointer slicing.
  • Language Validation (en Primary, Cross-Lingual Experimental): Fine-tuning and all benchmarks in this repository target English (en) text. While the underlying SentencePiece vocabulary can tokenize German and other languages, non-English extraction is experimental and unvalidated.
  • Sentence & Paragraph Perception Window: Encoder inputs target structured clauses, sentences, and paragraph chunks (up to 384–512 word tokens—matching standard EHR notes, Kafka/Flink events, and RAG chunks). Long multi-page documents should be segmented by paragraph or section prior to extraction.
  • Schema & Threshold Calibration: Confidence thresholds (entity_threshold = 0.35–0.50, relation_threshold = 0.40–0.55) can be adjusted per downstream precision/recall profile, and highly specialized domain predicates benefit from targeted fine-tuning.

🔌 ONNX Graph Input / Output Contract

  • Pre-Tokenized Input Sequence: ["<<ENT>>", e_0, ..., "<<SEP>>", "<<REL>>", r_0, ..., "<<SEP>>", word_0, word_1, ...] where words_mask assigns 1..num_words to the first subtoken of each word and 0 to prompt/continuation/special tokens.
  • Inputs: input_ids (int64 [1, seq_len]), attention_mask (int64 [1, seq_len]), words_mask (int64 [1, seq_len]), text_lengths (int64 [1, 1]), plus span_idx (int64 [1, num_spans, 2]) & span_mask (bool [1, num_spans]) on span-level models/large/.
  • Outputs: logits, rel_idx (int64 [1, num_pairs, 2] rectangular span-grid index start_word * 12 + width), rel_logits (float32 [1, num_pairs, num_rel_classes]), and rel_mask (bool [1, num_pairs]).

🏛️ How This Powers Neuro-Symbolic AI in YPipe & Further Reading

Inside YPipe — The Sovereign Neurosymbolic Local-First AI Platform developed by iunera, fast CPU neural extraction acts as the perception stage of the neuro-symbolic YPipe Manifold Engine—translating unstructured prompts and documents into structured entities and relations before deterministic symbolic reasoning governs tool execution and local 800M–32B models across local workstations and on-premise hospital or enterprise servers.

🌐 Request an Evaluation Build or Live Demo

📖 Related Research & Engineering Articles on the iunera Blog

▶️ Watch Live Neuro-Symbolic AI & GLiNER Benchmarks on YouTube (@iunera)


🙏 Acknowledgments, Standards & License

We extend our sincere thanks to the open-weights researchers and standards communities whose work made this research prototype possible:

Released under the Apache License 2.0 (LICENSE).

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · gliner

Нельзя запустить

Модели GLiNER требуют отдельного рантайма.

Ревизия весов
bc0f023

0 моделей