File size: 8,617 Bytes
4467a39
 
 
 
 
de57b22
4467a39
 
 
 
 
 
 
de57b22
4467a39
 
 
 
 
8da591b
695f3a4
8da591b
695f3a4
de57b22
695f3a4
de57b22
695f3a4
de57b22
695f3a4
8da591b
 
 
 
695f3a4
de57b22
695f3a4
8da591b
695f3a4
8da591b
 
de57b22
8da591b
 
 
 
 
 
 
 
 
 
de57b22
695f3a4
8da591b
 
de57b22
8da591b
de57b22
8da591b
 
695f3a4
de57b22
 
 
 
 
 
 
 
8da591b
 
 
 
 
de57b22
 
 
 
 
 
 
 
 
 
 
 
 
695f3a4
de57b22
695f3a4
8da591b
695f3a4
8da591b
695f3a4
8da591b
 
 
 
 
 
 
 
695f3a4
de57b22
695f3a4
8da591b
695f3a4
de57b22
 
 
695f3a4
8da591b
695f3a4
8da591b
 
 
695f3a4
8da591b
695f3a4
8da591b
 
 
 
 
 
 
 
 
 
 
 
 
 
695f3a4
de57b22
695f3a4
8da591b
695f3a4
8da591b
 
 
695f3a4
8da591b
695f3a4
8da591b
 
 
de57b22
 
 
 
8da591b
 
 
 
 
 
 
 
 
 
 
695f3a4
de57b22
695f3a4
8da591b
695f3a4
de57b22
695f3a4
8da591b
de57b22
8da591b
695f3a4
de57b22
695f3a4
8da591b
 
 
de57b22
695f3a4
5454a70
695f3a4
de57b22
 
 
695f3a4
de57b22
 
 
 
 
 
 
8da591b
 
de57b22
 
 
 
8da591b
 
695f3a4
de57b22
8da591b
 
 
 
695f3a4
8da591b
de57b22
 
8da591b
695f3a4
de57b22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695f3a4
8da591b
695f3a4
de57b22
695f3a4
8da591b
695f3a4
de57b22
 
 
695f3a4
8da591b
695f3a4
8da591b
 
 
 
 
de57b22
8da591b
695f3a4
8da591b
695f3a4
8da591b
 
 
695f3a4
8da591b
695f3a4
de57b22
695f3a4
8da591b
695f3a4
8da591b
695f3a4
de57b22
 
 
 
8da591b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
---
language:
  - en
license: apache-2.0
library_name: transformers
pipeline_tag: text-generation
tags:
  - named-entity-recognition
  - ner
  - qwen
  - decoder-only
  - lora
  - conll2003
  - information-extraction
base_model: Qwen/Qwen2.5-0.5B-Instruct
datasets:
  - lhoestq/conll2003
---

# English Named Entity Recognition (NER) – Qwen2.5-0.5B-Instruct + LoRA

## Model Description

**Qwen-NER-Decoder** is a fine-tuned decoder-only Named Entity Recognition (NER) model based on [Qwen/Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct).

The model identifies and extracts named entities from English text and generates structured JSON output.

It is fine-tuned on the CoNLL-2003 English Named Entity Recognition dataset and recognizes four entity categories:

- **PER** – Person
- **ORG** – Organization
- **LOC** – Location
- **MISC** – Miscellaneous

The model uses **Low-Rank Adaptation (LoRA)** for parameter-efficient fine-tuning. The Hugging Face repository contains the LoRA adapter, so it must be loaded together with its original base model.

## Model Details

| Property | Details |
|---|---|
| Model Name | Qwen-NER-Decoder |
| Base Model | Qwen/Qwen2.5-0.5B-Instruct |
| Architecture | Decoder-only Transformer |
| Fine-tuning Method | LoRA |
| LoRA Rank | 8 |
| LoRA Alpha | 16 |
| LoRA Dropout | 0.05 |
| Training Epochs | 1 |
| Language | English |
| Task | Named Entity Recognition |
| Output Format | JSON |
| Training Framework | PyTorch, Transformers, PEFT |

## Dataset

The model was fine-tuned using the [CoNLL-2003 English NER dataset](https://huggingface.co/datasets/lhoestq/conll2003).

Dataset repository: `lhoestq/conll2003`

The dataset contains English sentences annotated with BIO-style named entity labels.

The four entity categories are:

| Label | Description |
|---|---|
| PER | Person |
| ORG | Organization |
| LOC | Location |
| MISC | Miscellaneous |

## Training Configuration

The model was fine-tuned using LoRA with the following configuration:

| Configuration | Value |
|---|---|
| Base Model | Qwen2.5-0.5B-Instruct |
| LoRA Rank | 8 |
| LoRA Alpha | 16 |
| LoRA Dropout | 0.05 |
| Target Modules | q_proj, k_proj, v_proj, o_proj |
| Training Epochs | 1 |
| Training Samples | Up to 8,000 |
| Validation Samples | 1,000 |
| Training Precision | FP16 |
| Optimizer | AdamW |
| Training Environment | Kaggle GPU |

LoRA adapts selected attention projection layers without updating all the parameters of the original base model.

## Evaluation Results

The model was evaluated on a quick test subset of 100 English sentences using exact entity-level matching.

| Metric | Score |
|---|---:|
| Precision | 90.40% |
| Recall | 81.63% |
| F1-score | 85.79% |
| True Positives | 160 |
| False Positives | 17 |
| False Negatives | 36 |

**Evaluation note:** These results represent the 100-sample evaluation subset, not the complete test dataset. They should not be interpreted as a full-dataset benchmark.

Additional manually selected English sentences were used to inspect entity extraction behavior.

## Example Predictions

### Example 1

**Input:**

```text
Elon Musk founded SpaceX.
```

**Output:**

```json
{
  "entities": [
    {
      "text": "Elon Musk",
      "type": "PER"
    },
    {
      "text": "SpaceX",
      "type": "ORG"
    }
  ]
}
```

### Example 2

**Input:**

```text
Barack Obama visited Microsoft headquarters in Seattle.
```

**Output:**

```json
{
  "entities": [
    {
      "text": "Barack Obama",
      "type": "PER"
    },
    {
      "text": "Microsoft",
      "type": "ORG"
    },
    {
      "text": "Seattle",
      "type": "LOC"
    }
  ]
}
```

*Examples illustrate the intended output structure.*

## How to Use

### 1. Install Dependencies

```bash
pip install torch transformers peft accelerate safetensors
```

### 2. Load the Base Model and LoRA Adapter

```python
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftConfig, PeftModel

ADAPTER_MODEL = "ullahhafeez321/Qwen-NER-Decoder"

# Read the original base model from the adapter configuration
adapter_config = PeftConfig.from_pretrained(ADAPTER_MODEL)
BASE_MODEL = adapter_config.base_model_name_or_path

# Load tokenizer from the base model
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)

if tokenizer.pad_token_id is None:
    tokenizer.pad_token = tokenizer.eos_token

# Load the original Qwen base model
base_model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    torch_dtype=(
        torch.float16 if torch.cuda.is_available()
        else torch.float32
    ),
    device_map="auto"
)

# Attach the fine-tuned LoRA adapter
model = PeftModel.from_pretrained(
    base_model,
    ADAPTER_MODEL
)

model.eval()

print("Qwen NER model loaded successfully!")
```

### 3. Run Inference

The prompt used during inference should follow the same instruction and output format used during fine-tuning.

The following is an illustrative JSON extraction example:

```python
sentence = "Albert Einstein worked at Princeton University."

prompt = f"""
Extract named entities from the following sentence.

Entity types:
PER = Person
ORG = Organization
LOC = Location
MISC = Miscellaneous

Return only a JSON array:

[
  {{"text": "entity name", "type": "PER"}}
]

If no entities are found, return [].

Sentence: {sentence}

Entities:
"""

inputs = tokenizer(
    prompt,
    return_tensors="pt",
    truncation=True,
    max_length=1024
)

input_device = model.get_input_embeddings().weight.device
inputs = {
    key: value.to(input_device)
    for key, value in inputs.items()
}

with torch.inference_mode():
    outputs = model.generate(
        **inputs,
        max_new_tokens=150,
        do_sample=False,
        pad_token_id=tokenizer.pad_token_id,
        eos_token_id=tokenizer.eos_token_id
    )

generated_tokens = outputs[0][inputs["input_ids"].shape[1]:]

result = tokenizer.decode(
    generated_tokens,
    skip_special_tokens=True
)

print(result)
```

**Note:** This example demonstrates the inference process. For the best results, use the exact prompt template and target format used to train the uploaded adapter.

## Intended Use

This model is intended for:

- English named entity recognition.
- Natural Language Processing applications.
- Information extraction systems.
- Text analysis and document processing.
- Educational and research projects.
- Integration with sentiment classification systems.
- Applications that require structured entity extraction.

## Limitations

- The model may occasionally miss named entities.
- Some entities may receive incorrect classifications.
- Entity boundaries and spelling may occasionally be incorrect.
- Performance can vary across different domains and writing styles.
- The reported evaluation score is based on a limited 100-sample test subset.
- The model is intended for English text and may not perform reliably on other languages.
- The model is not intended to replace human verification in critical applications.

## Model Architecture

This project uses a decoder-only Transformer architecture based on Qwen2.5-0.5B-Instruct.

The model generates structured entity extraction results from an English input sentence.

LoRA fine-tuning adapts selected attention projection layers while preserving the original base model weights.

The uploaded Hugging Face repository contains the fine-tuned adapter rather than a complete standalone model checkpoint.

## Future Improvements

- Increase training data and training epochs.
- Improve recall and entity coverage.
- Evaluate performance on the complete test dataset.
- Improve entity boundary detection.
- Expand evaluation across different English text domains.
- Improve inference consistency and structured JSON generation.
- Integrate with an encoder-only BERT sentiment classification model.

## Acknowledgements

- [Qwen Team](https://huggingface.co/Qwen) for the Qwen2.5 base model.
- [CoNLL-2003](https://huggingface.co/datasets/lhoestq/conll2003) dataset contributors.
- [Hugging Face](https://huggingface.co/) for the Transformers, Datasets, and PEFT ecosystem.

## License

The adapter repository declares the Apache-2.0 license. Please also review the original base model and dataset licenses and their respective usage conditions before redistribution or commercial use.

---

**Project:** English Named Entity Recognition using a Decoder-only Transformer with LoRA Fine-tuning.

**Model Repository:** `ullahhafeez321/Qwen-NER-Decoder`

**Base Model:** `Qwen/Qwen2.5-0.5B-Instruct`

**Frameworks:** PyTorch, Transformers, PEFT, Hugging Face Datasets.