Run this model with HF Jobs

Run ipsnan/keywordsextraction on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/ipsnan/keywordsextraction. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/ipsnan/keywordsextraction on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 7,578 Bytes
ac4d46b
 
1542f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac4d46b
5a72970
1542f11
5a72970
1542f11
5a72970
1542f11
5a72970
1542f11
5a72970
1542f11
5a72970
 
 
1542f11
5a72970
1542f11
 
 
 
 
 
 
5a72970
1542f11
5a72970
1542f11
 
 
 
 
 
 
5a72970
 
 
1542f11
5a72970
1542f11
 
 
 
 
 
5a72970
1542f11
5a72970
1542f11
 
 
 
 
5a72970
 
 
1542f11
5a72970
1542f11
5a72970
1542f11
 
 
 
 
 
 
 
 
 
 
 
5a72970
 
 
 
 
1542f11
5a72970
1542f11
 
5a72970
 
 
1542f11
 
 
5a72970
1542f11
 
 
 
 
 
 
5a72970
1542f11
 
5a72970
 
1542f11
5a72970
1542f11
5a72970
1542f11
 
5a72970
1542f11
 
 
5a72970
1542f11
5a72970
1542f11
 
 
 
5a72970
1542f11
5a72970
 
 
 
 
1542f11
5a72970
 
 
 
 
 
 
1542f11
 
 
5a72970
1542f11
5a72970
1542f11
 
 
 
5a72970
1542f11
5a72970
1542f11
 
5a72970
 
 
1542f11
 
ac4d46b
 
 
 
 
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
---
tags:
- sentence-transformers
- sentence-similarity
- feature-extraction
- information-retrieval
- dense
base_model: intfloat/multilingual-e5-base
language:
- uk
license: mit
pipeline_tag: sentence-similarity
library_name: sentence-transformers
metrics:
- cosine_accuracy@1
- cosine_accuracy@5
- cosine_accuracy@10
- cosine_precision@5
- cosine_precision@10
- cosine_recall@5
- cosine_recall@10
- cosine_ndcg@10
- cosine_mrr@10
- cosine_map@10
model-index:
- name: keywordsextraction
  results:
  - task:
      type: information-retrieval
      name: Information Retrieval
    dataset:
      name: kw retrieval
      type: kw_retrieval
    metrics:
    - type: cosine_accuracy@1
      value: 0.965
      name: Cosine Accuracy@1
    - type: cosine_accuracy@5
      value: 0.995
      name: Cosine Accuracy@5
    - type: cosine_accuracy@10
      value: 0.995
      name: Cosine Accuracy@10
    - type: cosine_precision@5
      value: 0.7835
      name: Cosine Precision@5
    - type: cosine_precision@10
      value: 0.464
      name: Cosine Precision@10
    - type: cosine_recall@5
      value: 0.8075
      name: Cosine Recall@5
    - type: cosine_recall@10
      value: 0.9143
      name: Cosine Recall@10
    - type: cosine_ndcg@10
      value: 0.9184
      name: Cosine Ndcg@10
    - type: cosine_mrr@10
      value: 0.9773
      name: Cosine Mrr@10
    - type: cosine_map@10
      value: 0.8754
      name: Cosine Map@10
---

# 🇺🇦 Keyword Extraction via Bi-Encoder Retrieval (Ukrainian)

## 📌 Overview

This repository contains a **sentence-transformers bi-encoder** fine-tuned for **extracting keywords from Ukrainian scientific and business documents**.

Unlike a generative LLM, this model does not *write* keywords — it **retrieves** them. The document is encoded into the same vector space as a pre-built index of candidate keywords, and the closest keywords by cosine similarity are returned. This makes the model much smaller and faster than a generative LoRA-tuned LLM, while reaching very high retrieval accuracy on the evaluation set (see [Evaluation](#-evaluation)).

> ℹ️ This replaces the previous generative approach (LoRA adapter on `meta-llama/Llama-3.1-8B-Instruct`) with a dedicated retrieval model.

---

## 🧠 Base Model

* **Base model:** [`intfloat/multilingual-e5-base`](https://huggingface.co/intfloat/multilingual-e5-base)
* **Architecture:** XLM-RoBERTa encoder + mean pooling + L2 normalization
* **Fine-tuning method:** Full fine-tuning with `MultipleNegativesRankingLoss`
* **Library:** Sentence Transformers
* **Output dimensionality:** 768
* **Max sequence length:** 512 tokens
* **Similarity function:** Cosine similarity

### Full Model Architecture

```
SentenceTransformer(
  (0): Transformer({'max_seq_length': 512, 'do_lower_case': False, 'architecture': 'XLMRobertaModel'})
  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_mean_tokens': True})
  (2): Normalize()
)
```

---

## 📊 Dataset & Training

* Training pairs: **78,648** `(document, keyword)` samples built from a corpus of Ukrainian scientific/business documents (see `dataset_full.jsonl` used at training time — not included in this repo, only the resulting keyword index is).
* Query/passage format follows the E5 convention:
  * Documents are prefixed with `query: `
  * Keywords are prefixed with `passage: `
* Loss: `MultipleNegativesRankingLoss` (in-batch negatives, `scale=20.0`)
* Epochs: 3, batch size 96 (grad. accumulation 2), learning rate 2e-5, bf16

### Training Logs

| Epoch | Step | Training Loss | cosine_ndcg@10 |
|:-----:|:----:|:--------------:|:---------------:|
| 1.0   | 410  | –              | 0.9085           |
| 2.0   | 820  | –              | 0.9157           |
| **3.0** | **1230** | **–**    | **0.9184**       |

---

## 📈 Evaluation

Evaluated with [`InformationRetrievalEvaluator`](https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html#sentence_transformers.evaluation.InformationRetrievalEvaluator) on held-out `(document, keyword)` pairs:

| Metric              | Value      |
|:--------------------|:-----------|
| cosine_accuracy@1   | 0.965      |
| cosine_accuracy@5   | 0.995      |
| cosine_accuracy@10  | 0.995      |
| cosine_precision@5  | 0.7835     |
| cosine_precision@10 | 0.464      |
| cosine_recall@5     | 0.8075     |
| cosine_recall@10    | 0.9143     |
| **cosine_ndcg@10**  | **0.9184** |
| cosine_mrr@10       | 0.9773     |
| cosine_map@10       | 0.8754     |

---

## 🚀 Usage

### 1. Raw embeddings (Sentence Transformers)

```bash
pip install -U sentence-transformers
```

```python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("ipsnan/keywordsextraction")

sentences = [
    "query: Штучний інтелект активно використовується у промисловості для автоматизації процесів...",
    "passage: штучний інтелект",
    "passage: автоматизація процесів",
]
embeddings = model.encode(sentences)
print(embeddings.shape)  # [3, 768]

similarities = model.similarity(embeddings, embeddings)
print(similarities)
```

### 2. Full keyword extraction pipeline (PDF → keywords)

This repository also ships `keyword_index.pkl` — embeddings of every unique keyword seen during training — and `infer_keywords.py`, the retrieval script used to go from a raw PDF document straight to a ranked keyword list.

```bash
pip install -U sentence-transformers pymupdf numpy

python infer_keywords.py /path/to/file.pdf
python infer_keywords.py /path/to/file.pdf --top-k 10 --threshold 0.5
```

Under the hood the script:

1. Extracts and cleans text from the PDF (`1fullsourcedata.py`).
2. Encodes the first ~3000 characters of the document with this model, prefixed with `query: `.
3. Looks up the nearest keyword vectors in `keyword_index.pkl` by cosine similarity.
4. Returns the top-K keywords above `--threshold`.

To rebuild the keyword index from scratch you need the original `dataset_full.jsonl` training corpus and can run `python infer_keywords.py <pdf> --rebuild-index`.

---

## 🎯 Task

**Keyword extraction (Ukrainian NLP)**, optimized for:

* scientific texts
* academic content
* business documents

## ⚠️ Limitations

* Works best with Ukrainian-language texts.
* Can only return keywords that already exist in `keyword_index.pkl` (it is a retrieval model, not a generative one) — rebuild the index on your own keyword set to extend coverage.
* Performance depends on how representative the first ~3000 characters of the document are (title + abstract).

## 📦 Repository Contents

* `model.safetensors`, `config.json`, `config_sentence_transformers.json`, `modules.json`, `sentence_bert_config.json`, `tokenizer.json`, `tokenizer_config.json`, `1_Pooling/`, `2_Normalize/` — the Sentence Transformers model
* `keyword_index.pkl` — pre-computed keyword embeddings used for retrieval
* `infer_keywords.py` — end-to-end PDF → keywords inference script
* `1fullsourcedata.py` — PDF text extraction/cleaning helper used by `infer_keywords.py`

## 📜 License

* Model weights: MIT
* Base model: subject to the [`intfloat/multilingual-e5-base`](https://huggingface.co/intfloat/multilingual-e5-base) license (MIT)

## 🙌 Acknowledgments

* [intfloat/multilingual-e5-base](https://huggingface.co/intfloat/multilingual-e5-base)
* Sentence Transformers / Hugging Face ecosystem


## Download model

[Download](/ipsnan/keywordsextraction/tree/main) them in the Files & versions tab.