--- base_model: unsloth/Phi-4-mini-instruct-bnb-4bit library_name: peft model_name: n1_entity_extraction_model_r512_dropout tags: - base_model:adapter:unsloth/Phi-4-mini-instruct-bnb-4bit - lora - sft - transformers - unsloth licence: license pipeline_tag: text-generation license: apache-2.0 datasets: - UWV/wim-instruct-wiki-to-jsonld-agent-steps language: - nl --- # Phi-4-mini N1 Entity Extraction Fine-tune This model is a fine-tuned version of [microsoft/Phi-4-mini-instruct](https://huggingface.co/microsoft/Phi-4-mini-instruct) optimized for entity extraction from Dutch text, trained as part of the WIM (Wikipedia to Knowledge Graph) pipeline. ## Model Details ### Model Description - **Developed by:** UWV InnovatieHub - **Model type:** Causal Language Model with LoRA fine-tuning - **Language(s):** Dutch (nl) - **License:** MIT - **Finetuned from:** microsoft/Phi-4-mini-instruct (3.82B parameters) - **Training Framework:** Unsloth (optimized training, not TRL) ### Training Details - **Dataset:** [UWV/wim-instruct-wiki-to-jsonld-agent-steps](https://huggingface.co/datasets/UWV/wim-instruct-wiki-to-jsonld-agent-steps) - **Dataset Size:** 9,272 N1-specific examples (entity extraction tasks) - **Training Duration:** 6 hours 22 minutes - **Hardware:** NVIDIA A100 80GB - **Epochs:** 3.48 - **Steps:** 2,000 - **Training Metrics:** - Final Training Loss: 0.5206 - Final Eval Loss: 0.4303 - Training samples/second: 1.395 - Gradient norm (final): ~0.42 ### LoRA Configuration ```python { "r": 512, # Rank "lora_alpha": 1024, # Alpha (2:1 ratio) "lora_dropout": 0.05, # Dropout "bias": "none", "task_type": "CAUSAL_LM", "target_modules": [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ] } ``` ### Training Configuration ```python { "model": "phi4-mini", "max_seq_length": 16384, "batch_size": 16, "gradient_accumulation_steps": 1, "effective_batch_size": 16, "learning_rate": 2e-5, "warmup_steps": 50, "max_grad_norm": 1.0, "lr_scheduler": "linear", "optimizer": "paged_adamw_8bit", "bf16": True, "seed": 42 } ``` ## Intended Uses & Limitations ### Intended Uses - **Entity Extraction**: Extract named entities, concepts, and relationships from Dutch text - **Knowledge Graph Construction**: First step (N1) in the WIM pipeline for converting text to structured data - **Information Extraction**: Identify people, organizations, locations, dates, and other entities ### Limitations - Optimized for Dutch Wikipedia-style text - Best performance on encyclopedic content - May require adaptation for domain-specific entity types - Context window limited to 16K tokens ## How to Use ### Option 1: Using the Merged Model (Recommended) ```python from transformers import AutoModelForCausalLM, AutoTokenizer import torch import json # Load the merged model (ready to use) model = AutoModelForCausalLM.from_pretrained( "UWV/wim-n1-phi4-mini-merged", torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True ) tokenizer = AutoTokenizer.from_pretrained("UWV/wim-n1-phi4-mini-merged") # Prepare input text = """ De Schijfwereld is een fantasiewereld uit de boeken van Terry Pratchett. Het is een platte planeet die op de ruggen van vier reusachtige olifanten rust: Berilia, Tubul, Groothuis T'Phon en Jerakeen. Deze olifanten staan op hun beurt op de rug van de Groot A'Tuin, een enorme schildpad die door de kosmos zwemt. """ messages = [ { "role": "system", "content": "Je bent een expert in het extraheren van entiteiten uit tekst." }, { "role": "user", "content": f"""Analyseer de gegeven Nederlandse tekst en voer de volgende taken uit: 1. Geef eerst een beknopte samenvatting van waar de tekst over gaat (maximaal 2 zinnen). 2. Identificeer alle belangrijke entiteiten in de tekst. Voor elke entiteit: - Gebruik de exacte naam zoals vermeld in de tekst - Bepaal het meest specifieke type/class dat bij deze entiteit past - Geef een korte beschrijving van wat dit type/class vertegenwoordigt 3. Identificeer de relaties tussen de gevonden entiteiten. Hier zijn enkele voorbeelden van output van entiteiten en relaties. Het pijp-karakter (|) wordt gebruikt om velden te scheiden. BELANGRIJK: Zorg ervoor dat het TYPE/CLASS zowel SPECIFIEK als CORRECT is. ### Voorbeeld van entiteiten De Koe | Straat | Een straat Amsterdam | Stad | Een stad of dorp Pedro Nunesplein | Plein | Een plein of open ruimte in een stad Statue of Pedro Nunes | Monument | Een gedenkteken, standbeeld of herdenkingsstructuur Pedro Nunes | Persoon | Portugese wiskundige, kosmograaf en professor Municipality of Amsterdam | Overheidsorganisatie | Een lokale overheidsinstantie of gemeente Universiteit Leiden | Onderwijsinstelling | Een universiteit, hogeschool of andere onderwijsinstantie 1502 | Datum | Een specifieke datum of jaartal 1578 | Datum | Een specifieke datum of jaartal Portugal | Land | Een land of natie Germany | Land | Een land of natie ### Voorbeeld van relaties Pedro Nunesplein | genoemd naar | Pedro Nunes Statue of Pedro Nunes | staat op | Pedro Nunesplein Statue of Pedro Nunes | afbeeldt | Pedro Nunes Pedro Nunes | geboren in | 1502 Pedro Nunes | gestorven in | 1578 Pedro Nunes | nationaliteit | Portugal Pedro Nunes | werkte bij | Universiteit Leiden Zoals je ziet wordt de format gebruikt van: [Entiteit naam] | [Type/Class] | [Beschrijving] Voor relaties: [Entiteit 1] | [relatie type] | [Entiteit 2] Tekst om te analyseren: {text}""" } ] # Apply chat template and generate prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=16384) inputs = {k: v.to(model.device) for k, v in inputs.items()} with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=1000, temperature=0.1, # Low temperature for structured output do_sample=True, top_p=0.95, pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id, ) # Decode response response = tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract just the assistant's response if "assistant:" in response: response = response.split("assistant:")[-1].strip() print(response) ``` ### Option 2: Using the LoRA Adapter ```python from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel import torch # Load base model base_model = AutoModelForCausalLM.from_pretrained( "microsoft/Phi-4-mini-instruct", torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True ) # Load adapter model = PeftModel.from_pretrained( base_model, "UWV/wim-n1-phi4-mini-adapter" ) tokenizer = AutoTokenizer.from_pretrained("UWV/wim-n1-phi4-mini-adapter") # Use same inference code as above... ``` ## Expected Output Format The model outputs structured text with entities and relations in a pipe-separated format: ``` De tekst beschrijft de Schijfwereld, een fantasiewereld uit Terry Pratchett's boeken. Het is een platte planeet die rust op vier olifanten, die op hun beurt op een reusachtige schildpad staan. Schijfwereld | FictionalPlace | Een verzonnen wereld of locatie uit fictie Terry Pratchett | Person | Een persoon Berilia | FictionalCharacter | Een verzonnen personage of wezen Tubul | FictionalCharacter | Een verzonnen personage of wezen Groothuis T'Phon | FictionalCharacter | Een verzonnen personage of wezen Jerakeen | FictionalCharacter | Een verzonnen personage of wezen Groot A'Tuin | FictionalCharacter | Een verzonnen personage of wezen Schijfwereld | gecreƫerd door | Terry Pratchett Schijfwereld | rust op | Berilia Schijfwereld | rust op | Tubul Schijfwereld | rust op | Groothuis T'Phon Schijfwereld | rust op | Jerakeen Berilia | staat op | Groot A'Tuin Tubul | staat op | Groot A'Tuin Groothuis T'Phon | staat op | Groot A'Tuin Jerakeen | staat op | Groot A'Tuin ``` ## Dataset Information The model was trained on the [UWV/wim-instruct-wiki-to-jsonld-agent-steps](https://huggingface.co/datasets/UWV/wim-instruct-wiki-to-jsonld-agent-steps) dataset, which contains: - **Source**: Dutch Wikipedia articles - **Processing**: Multi-agent pipeline converting text to JSON-LD - **N1 Examples**: 9,272 entity extraction tasks - **Format**: ChatML-formatted instruction-following examples - **Task**: Extract entities and prepare them for Schema.org mapping ## Model Versions - **Merged Model**: `UWV/wim-n1-phi4-mini-merged` (7.17 GB) - Ready to use without adapter loading - Recommended for production inference - **LoRA Adapter**: `UWV/wim-n1-phi4-mini-adapter` (~1.14 GB) - Requires base Phi-4-mini-instruct model - Useful for further fine-tuning or experiments ## Pipeline Context This model is part of the WIM (Wikipedia to Knowledge Graph) pipeline: 1. **N1 (This Model)**: Entity Extraction 2. **N2**: Schema.org Type Selection 3. **N3**: Transform to JSON-LD 4. **N4**: Validation 5. **N5**: Add Human-Readable Labels ## Citation If you use this model, please cite: ```bibtex @misc{wim-n1-phi4-mini, author = {UWV InnovatieHub}, title = {Phi-4-mini N1 Entity Extraction Model}, year = {2025}, publisher = {HuggingFace}, url = {https://huggingface.co/UWV/wim-n1-phi4-mini-merged} } ```