Instructions to use gpancardo/beto-pii with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use gpancardo/beto-pii with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="gpancardo/beto-pii")# Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("gpancardo/beto-pii") model = AutoModelForTokenClassification.from_pretrained("gpancardo/beto-pii") - Notebooks
- Google Colab
- Kaggle
beto-pii
Model Overview
beto-pii is a fine-tuned version of dccuchile/bert-base-spanish-wwm-cased (BETO) for token-level PII detection in Spanish text. It uses a BIO tagging scheme to identify and classify 24 types of personally identifiable information.
Architecture: BERT-base (12 layers, 768 hidden, 12 heads) — 110M parameters.
Training data: Spanish subset of ai4privacy/pii-masking-200k (25,651 training samples).
Output format: Token classification over a BIO label space (O + B-{type} + I-{type} for each PII type).
Tokenizer: WordPiece (cased) — respects uppercase/lowercase distinction, critical for name entities.
This model is the native Spanish encoder in a comparative study of PII detection across monolingual (BETO) and multilingual (XLM-RoBERTa, mDeBERTa) architectures, and across classical (regex, Presidio), encoder-based, and SLM-based detectors.
Why BETO?
BETO is a BERT model trained exclusively on Spanish corpora (Spanish Wikipedia, Opus, and other Spanish web text). Its vocabulary and pretraining distribution are optimized for Spanish, giving it an advantage on Spanish-specific linguistic patterns — particularly relevant for name structure (compound surnames, multi-word given names), Spanish document IDs (DNI, NIE), and address formats.
Intended Use
Primary use case: Identifying PII spans in Spanish text for data masking, anonymization, or redaction pipelines.
Suitable for:
- Spanish text with personal data (names, emails, phones, addresses, IDs, financial data)
- Single-document inference and batch processing
- Integration via Hugging Face
pipelineor directtransformersusage - Serving behind a tokenization proxy for privacy-preserving inference
Not suitable for:
- Non-Spanish text (use XLM-R or mDeBERTa variants for multilingual input)
- Detection without context (single tokens out of context)
- Adversarial or heavily obfuscated text
- Real-time low-latency scenarios without optimization (see Performance section)
Training Data
Dataset: ai4privacy/pii-masking-200k — Spanish split.
Split statistics (seed 42):
| Split | Samples |
|---|---|
| Train | 25,651 |
| Validation | 5,485 |
| Test | 5,527 |
Label canonicalization: 28 raw PII types are collapsed to 24 canonical labels. Name components (GIVENNAME1, GIVENNAME2, LASTNAME1, LASTNAME2, LASTNAME3) are unified under PERSON. All other types (EMAIL, PHONE, IP_ADDRESS, STREET_ADDRESS, CREDIT_CARD, IDCARD, etc.) pass through unchanged.
Note: This is synthetic data generated for PII masking research. It is not real personal data.
Training Procedure
Hyperparameters
| Parameter | Value |
|---|---|
| Model | dccuchile/bert-base-spanish-wwm-cased |
| Max sequence length | 256 tokens |
| Training epochs | 3 |
| Batch size (per device) | 16 |
| Learning rate | 5e-5 |
| Weight decay | 0.01 |
| Optimizer | AdamW (defaults) |
| LR scheduler | Linear decay |
| Warmup | None (implicit in Trainer) |
| FP16 | Enabled |
| Seed | 42 |
| Evaluation strategy | Every epoch |
| Save strategy | Every epoch |
| Load best model at end | Yes (metric: token F1) |
| Dataloader workers | 2 |
Hardware
Trained on a single GPU (NVIDIA T4 or P100, ~15–30 min depending on GPU). Both compute capabilities (SM 60 for P100, SM 75 for T4) are supported via PyTorch 2.4.0.
Environmental Impact
| Component | Estimate |
|---|---|
| GPU | 1× NVIDIA T4 (70 W TDP) |
| Training time | ~20 min |
| Energy | ~0.02 kWh |
| CO₂e (estimate) | ~0.01 kg |
How to Use
With pipeline (recommended)
from transformers import pipeline
pipe = pipeline("token-classification", model="gpancardo/beto-pii")
text = "Me llamo Juan Pérez y mi correo es juan.perez@correo.com"
results = pipe(text)
for r in results:
print(f"{r['entity']}: {r['word']} (score={r['score']:.3f})")
With AutoModel + AutoTokenizer
from transformers import AutoTokenizer, AutoModelForTokenClassification
import torch
tokenizer = AutoTokenizer.from_pretrained("gpancardo/beto-pii")
model = AutoModelForTokenClassification.from_pretrained("gpancardo/beto-pii")
text = "El DNI de María López es 12345678Z"
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=256)
with torch.no_grad():
logits = model(**inputs).logits
preds = torch.argmax(logits, dim=-1).squeeze().tolist()
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"].squeeze().tolist())
id2label = model.config.id2label
for token, pred in zip(tokens, preds):
label = id2label[pred]
if label != "O":
print(f"{token} → {label}")
With ONNX for production
pip install optimum onnxruntime
optimum-cli export onnx --model gpancardo/beto-pii beto-pii-onnx
Performance
Evaluation results will be populated after the benchmark suite completes. Expected detection F1 > 0.7 on Spanish test based on validation runs.
Metrics reported:
- Detection F1 — span overlap (IoU ≥ 0.5), type-agnostic (primary)
- Typification F1 — span + exact type match (secondary)
- Per-type precision, recall, and F1
- 95% bootstrap confidence intervals
Limitations & Biases
- Synthetic training data: The model was trained on synthetically generated PII. Distributional shifts may occur on real-world text.
- Spanish-only: Language coverage is limited to Spanish. For multilingual input, use the XLM-R or mDeBERTa variants.
- Context window: Limited to 256 tokens. Longer documents need sliding-window or chunking strategies.
- Adversarial robustness: Not tested against obfuscation, misspellings, or adversarial perturbations.
- Implicit biases: The underlying BETO model may encode societal biases present in its Spanish pretraining corpus.
License
MIT
beto-pii
Resumen del modelo
beto-pii es una versión fine-tuned de dccuchile/bert-base-spanish-wwm-cased (BETO) para detección de PII a nivel de token en texto en español. Utiliza un esquema de etiquetado BIO para identificar y clasificar 24 tipos de información personal identificable.
Arquitectura: BERT-base (12 capas, 768 ocultos, 12 cabezas) — 110M parámetros.
Datos de entrenamiento: Subconjunto en español de ai4privacy/pii-masking-200k (25,651 muestras de entrenamiento).
Formato de salida: Clasificación de tokens sobre un espacio de etiquetas BIO (O + B-{tipo} + I-{tipo} para cada tipo de PII).
Tokenizador: WordPiece (cased) — respeta mayúsculas/minúsculas, crítico para entidades nominativas.
Este modelo es el encoder nativo en español dentro de un estudio comparativo de detección de PII entre arquitecturas monolingües (BETO) y multilingües (XLM-RoBERTa, mDeBERTa), y entre detectores clásicos (regex, Presidio), basados en encoder y basados en SLM.
¿Por qué BETO?
BETO es un modelo BERT entrenado exclusivamente con corpus en español (Wikipedia en español, Opus y otros textos web en español). Su vocabulario y distribución de preentrenamiento están optimizados para el español, lo que le otorga ventaja en patrones lingüísticos específicos del español — particularmente relevantes para la estructura de nombres (apellidos compuestos, nombres de pila múltiples), identificaciones españolas (DNI, NIE) y formatos de direcciones.
Uso previsto
Caso de uso principal: Identificar spans de PII en texto en español para pipelines de enmascaramiento, anonimización o redacción.
Adecuado para:
- Texto en español con datos personales (nombres, correos, teléfonos, direcciones, identificaciones, datos financieros)
- Inferencia por documento individual y procesamiento por lotes
- Integración mediante
pipelinede Hugging Face o uso directo contransformers - Servicio detrás de un proxy de tokenización para inferencia con privacidad
No adecuado para:
- Texto que no sea en español (usar las variantes XLM-R o mDeBERTa para entrada multilingüe)
- Detección sin contexto (tokens aislados)
- Texto adversarial u ofuscado
- Escenarios de baja latencia en tiempo real sin optimización (ver sección Rendimiento)
Datos de entrenamiento
Dataset: ai4privacy/pii-masking-200k — split en español.
Estadísticas de los splits (seed 42):
| Split | Muestras |
|---|---|
| Train | 25,651 |
| Validation | 5,485 |
| Test | 5,527 |
Canonicalización de etiquetas: 28 tipos crudos de PII se colapsan a 24 etiquetas canónicas. Los componentes de nombre (GIVENNAME1, GIVENNAME2, LASTNAME1, LASTNAME2, LASTNAME3) se unifican bajo PERSON. Todos los demás tipos (EMAIL, PHONE, IP_ADDRESS, STREET_ADDRESS, CREDIT_CARD, IDCARD, etc.) pasan sin cambios.
Nota: Estos son datos sintéticos generados para investigación de enmascaramiento de PII. No son datos personales reales.
Procedimiento de entrenamiento
Hiperparámetros
| Parámetro | Valor |
|---|---|
| Modelo | dccuchile/bert-base-spanish-wwm-cased |
| Longitud máxima de secuencia | 256 tokens |
| Épocas | 3 |
| Batch size (por dispositivo) | 16 |
| Tasa de aprendizaje | 5e-5 |
| Weight decay | 0.01 |
| Optimizador | AdamW (predeterminados) |
| LR scheduler | Decaimiento lineal |
| Warmup | Ninguno (implícito en Trainer) |
| FP16 | Activado |
| Semilla | 42 |
| Estrategia de evaluación | Cada época |
| Estrategia de guardado | Cada época |
| Cargar mejor modelo al final | Sí (métrica: token F1) |
| Dataloader workers | 2 |
Hardware
Entrenado en una sola GPU (NVIDIA T4 o P100, ~15–30 min según la GPU). Ambas capacidades de cómputo (SM 60 para P100, SM 75 para T4) son compatibles mediante PyTorch 2.4.0.
Impacto ambiental
| Componente | Estimación |
|---|---|
| GPU | 1× NVIDIA T4 (70 W TDP) |
| Tiempo de entrenamiento | ~20 min |
| Energía | ~0.02 kWh |
| CO₂e (estimado) | ~0.01 kg |
Cómo usar
Con pipeline (recomendado)
from transformers import pipeline
pipe = pipeline("token-classification", model="gpancardo/beto-pii")
texto = "Me llamo Juan Pérez y mi correo es juan.perez@correo.com"
resultados = pipe(texto)
for r in resultados:
print(f"{r['entity']}: {r['word']} (score={r['score']:.3f})")
Con AutoModel + AutoTokenizer
from transformers import AutoTokenizer, AutoModelForTokenClassification
import torch
tokenizer = AutoTokenizer.from_pretrained("gpancardo/beto-pii")
model = AutoModelForTokenClassification.from_pretrained("gpancardo/beto-pii")
texto = "El DNI de María López es 12345678Z"
inputs = tokenizer(texto, return_tensors="pt", truncation=True, max_length=256)
with torch.no_grad():
logits = model(**inputs).logits
preds = torch.argmax(logits, dim=-1).squeeze().tolist()
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"].squeeze().tolist())
id2label = model.config.id2label
for token, pred in zip(tokens, preds):
etiqueta = id2label[pred]
if etiqueta != "O":
print(f"{token} → {etiqueta}")
Con ONNX para producción
pip install optimum onnxruntime
optimum-cli export onnx --model gpancardo/beto-pii beto-pii-onnx
Rendimiento
Los resultados de evaluación se completarán después de ejecutar el suite de benchmark. Se espera un F1 de detección > 0.7 en el test de español basado en ejecuciones de validación.
Métricas reportadas:
- F1 de detección — solapamiento de span (IoU ≥ 0.5), sin tipo (principal)
- F1 de tipificación — span + coincidencia exacta de tipo (secundaria)
- Precisión, recall y F1 por tipo
- Intervalos de confianza bootstrap al 95%
Limitaciones y sesgos
- Datos sintéticos de entrenamiento: El modelo se entrenó con PII generada sintéticamente. Pueden existir desplazamientos distribucionales en texto real.
- Solo español: La cobertura de idioma se limita al español. Para entrada multilingüe, usar las variantes XLM-R o mDeBERTa.
- Ventana de contexto: Limitada a 256 tokens. Documentos más largos necesitan estrategias de ventana deslizante o fragmentación.
- Robustez adversarial: No se ha probado contra ofuscación, errores ortográficos o perturbaciones adversariales.
- Sesgos implícitos: El modelo BETO subyacente puede codificar sesgos sociales presentes en su corpus de preentrenamiento en español.
Licencia
MIT
- Downloads last month
- 69
Dataset used to train gpancardo/beto-pii
Evaluation results
- Detection F1 on ai4privacy/pii-masking-200k (Spanish)test set self-reportedTBD
- Detection Precision on ai4privacy/pii-masking-200k (Spanish)test set self-reportedTBD
- Detection Recall on ai4privacy/pii-masking-200k (Spanish)test set self-reportedTBD