Multilingual mmBERT EuroVoc tagger (supersedes English RoBERTa)

#2
.gitattributes CHANGED
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  architecture.png filter=lfs diff=lfs merge=lfs -text
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  architecture.png filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,64 +1,137 @@
1
  ---
2
  license: eupl-1.2
 
 
 
3
  language:
4
  - en
5
- metrics:
6
- - type: f1
7
- value: 0.8345
8
- name: micro F1
9
- args:
10
- threshold: 0.46
11
- - type: NDCG@3
12
- value: 0.8819
13
- name: NDCG@5
14
- - type: NDCG@5
15
- value: 0.8689
16
- name: NDCG@5
17
- - type: NDCG@10
18
- value: 0.8780
19
- name: NDCG@10
 
 
 
 
 
 
 
 
20
  tags:
21
  - eurovoc
22
- pipeline_tag: text-classification
23
-
24
- widget:
25
- - text: "The Union condemns the continuing grave human rights violations by the Myanmar armed forces, including torture, sexual and gender-based violence, the persecution of civil society actors, human rights defenders and journalists, and attacks on the civilian population, including ethnic and religious minorities."
26
-
 
 
 
 
 
 
 
 
 
27
  ---
28
 
29
- # Eurovoc Multilabel Classifer 🇪🇺
30
 
31
- [EuroVoc](https://op.europa.eu/fr/web/eu-vocabularies) is a large multidisciplinary multilingual (24 languages of 🇪🇺) hierarchical thesaurus of more than 7000 classes covering the activities of EU institutions.
32
- Given the number of legal documents produced every day and the huge mass of pre-existing documents to be classified high quality automated or semi-automated classification methods are most welcome in this domain.
33
 
34
- This model based on BERT Deep Neural Network was trained on more than 3, 200,000 documents to achieve that task and is used in a production environment via the huggingface inference endpoint.
35
- This model support the 24 languages of the European Union.
36
 
37
  ## Architecture
38
 
39
- ![architecture](architecture.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- This classification model is built on top of [EUBERT](https://huggingface.co/EuropeanParliament/EUBERT) with 7331 Eurovoc labels
 
 
42
 
43
- With less than 100 million parameters, it can be deployed on commodity hardware without GPU acceleration (around 200 ms per inference for 2000 characters).
44
 
45
- Parameters :
46
- - Number of epochs 16
47
- - Batch size 10
48
- - Max lenght 512
49
- - Learning Rate 5e-05
50
 
51
  ## Usage
52
 
 
53
 
54
  ```python
55
- from eurovoc import EurovocTagger
56
- model = EurovocTagger.from_pretrained("EuropeanParliament/eurovoc_eu")
 
 
 
 
 
 
 
 
 
 
 
 
57
  ```
58
- see the source code also
59
 
60
- ## Author(s)
61
 
62
- Sébastien Campion <sebastien.campion@europarl.europa.eu>
63
 
64
- Andreas Papagiannis <andreas.papagiannis@europarl.europa.eu>
 
1
  ---
2
  license: eupl-1.2
3
+ base_model: jhu-clsp/mmBERT-base
4
+ pipeline_tag: text-classification
5
+ library_name: transformers
6
  language:
7
  - en
8
+ - fr
9
+ - de
10
+ - es
11
+ - it
12
+ - pt
13
+ - nl
14
+ - pl
15
+ - ro
16
+ - sv
17
+ - da
18
+ - fi
19
+ - cs
20
+ - sk
21
+ - sl
22
+ - hu
23
+ - bg
24
+ - el
25
+ - et
26
+ - lv
27
+ - lt
28
+ - hr
29
+ - mt
30
+ - ga
31
  tags:
32
  - eurovoc
33
+ - multi-label
34
+ - multilingual
35
+ - modernbert
36
+ - mmbert
37
+ metrics:
38
+ - type: f1
39
+ value: 0.733
40
+ name: Domain micro-F1
41
+ - type: f1
42
+ value: 0.621
43
+ name: Micro-thesaurus micro-F1
44
+ - type: f1
45
+ value: 0.429
46
+ name: Concept micro-F1
47
  ---
48
 
49
+ # EuroVoc Multilabel Classifier 🇪🇺 (multilingual)
50
 
51
+ [EuroVoc](https://op.europa.eu/en/web/eu-vocabularies) is the EU's large multidisciplinary, multilingual (24 languages) hierarchical thesaurus of more than 7,000 concepts covering the activities of the EU institutions. Given the volume of legal documents produced daily, high-quality automated or semi-automated subject classification is valuable in this domain.
 
52
 
53
+ This version supersedes the earlier English-only RoBERTa classifier: it is built on the multilingual [jhu-clsp/mmBERT-base](https://huggingface.co/jhu-clsp/mmBERT-base) encoder and reads documents in all 24 official EU languages natively, predicting 7,062 EuroVoc concept labels (multi-label).
 
54
 
55
  ## Architecture
56
 
57
+ `ModernBertModel` (mmBERT) encoder, then a masked mean-pool over token states, then a single linear head (`classifier.pt`) giving one logit per concept (sigmoid, BCE). No `trust_remote_code` is needed: the encoder is a standard `ModernBertModel` and the head loads from `classifier.pt`.
58
+
59
+ ## What it is for
60
+
61
+ A **tagging assistant**: it proposes tags, a person confirms them. At the broad subject level roughly **3 of 4 suggestions are correct and it finds about 7 of 10 of the correct ones**. It is not accurate enough to tag documents unattended at the most specific level, where it must pick one exact concept out of 7,062.
62
+
63
+ ## How good it is
64
+
65
+ Held-out validation set, 800 batches. EuroVoc is a 3-level hierarchy, and accuracy
66
+ depends heavily on which level you ask for.
67
+
68
+ | level | picks from | F1 (overall) | F1 (per label) | threshold |
69
+ |-------|-----------:|:------------:|:--------------:|:---------:|
70
+ | **Domain** | 21 broad subjects | **0.733** | 0.683 | 0.70 |
71
+ | **Micro-thesaurus** | 127 topics | **0.621** | 0.473 | 0.80 |
72
+ | **Concept** | 7,062 exact tags | **0.429** | 0.045 | 0.90 |
73
+
74
+ *F1 (overall)* weights every prediction equally; *F1 (per label)* averages each label's own score, so it is dominated by the thousands of rare concepts and sits much lower.
75
+ **Use the per-level thresholds above, not 0.5**: they are the tuned operating points.
76
+
77
+ ## Choosing an operating point
78
+
79
+ | use | level | threshold | suggestions correct | correct tags found |
80
+ |-----|-------|:---------:|:-------------------:|:------------------:|
81
+ | **default** (suggest-and-confirm) | Domain | 0.75 | 74% | 72% |
82
+ | precision-critical | Domain | 0.90 | 80% | 63% |
83
+ | mid-level suggest | Micro-thesaurus | 0.80 | 61% | 63% |
84
+
85
+ Raising the threshold trades finding fewer tags for being right more often.
86
+
87
+ ## Languages
88
+
89
+ Handles all 24 scripts natively, with no unreadable characters, and quality is close to uniform: best Swedish 0.507 and Spanish 0.500, English 0.488, lowest Maltese 0.466 and
90
+ Greek 0.468 (the share of a document's correct tags landing in the model's top 5). An
91
+ earlier version of this tagger used an English-only tokenizer and could not read Greek or
92
+ Cyrillic at all (65 to 68% of their characters were unknown); moving to mmBERT's
93
+ multilingual tokenizer fixed that, and it is where much of the overall gain came from.
94
+ Croatian and Irish have under 40 validation documents each, so treat their numbers as noise.
95
+
96
+ ## What makes it work
97
+
98
+ The one idea behind this model: each of the 7,062 concept classifiers is seeded from the meaning of its own EuroVoc **name** rather than a random start, so rarely-seen concepts inherit language understanding they could never learn from their handful of training documents. Measured against an earlier version of the model without this step (same architecture, same data, same evaluation), it lifts concept-level F1 by **11%** (0.385 to 0.429) and the rare-concept score by **20%** (0.038 to 0.045), with gains at every level.
99
+
100
+ ## Known limits
101
 
102
+ - **Picks a sibling or parent concept instead of the exact one.** The model reliably reads the subject but can choose a neighbouring vocabulary term at the most specific level. On a wood-industry document it predicted "wood product" and "sustainable forest management" where the annotator had written "wood industry" and "sustainable development": correct understanding, wrong vocabulary choice. This is the main reason concept-level scores trail the coarser levels, and the main reason to operate at Domain or Micro-thesaurus level for unattended use.
103
+ - **Rare concepts are still under-predicted.** Most of the 7,062 tags appear in very few documents; the name-based initialisation reduced this (per-label F1 +20%) but did not erase it. The concept-level tail remains the weakest area.
104
+ - **Long documents are cut at ~2,048 tokens** (about 68% fit whole; the median fits).
105
 
106
+ ## How it was trained
107
 
108
+ Fine-tuned from `jhu-clsp/mmBERT-base` on the EuroVoc CELLAR corpus (~327,000 unique
109
+ documents, 24 official languages). Trained in two stages on 3x NVIDIA RTX A5000, bf16
110
+ mixed precision, effective batch 216: a main run with the classifier seeded from EuroVoc name embeddings (learning rate 5e-5, ~9.9 passes over the data), then a short low-rate anneal (7.5e-6, ~2.2 passes) that produced the shipped checkpoint. Total training time roughly 35.5 hours (a 29h main run plus a 6h anneal), about 107 GPU-hours.
 
 
111
 
112
  ## Usage
113
 
114
+ The repo ships a `predict.py`, or inline:
115
 
116
  ```python
117
+ import torch, pickle, json
118
+ from huggingface_hub import hf_hub_download as dl
119
+ from transformers import AutoTokenizer, AutoModel
120
+ R = "EuropeanParliament/EuroVoc" # add revision="<branch>" while staged
121
+ tok = AutoTokenizer.from_pretrained(R); enc = AutoModel.from_pretrained(R).eval()
122
+ head = torch.load(dl(R, "classifier.pt"), weights_only=True)
123
+ mlb = pickle.load(open(dl(R, "mlb.pickle"), "rb")); names = json.load(open(dl(R, "names.json")))
124
+ b = tok("your EU document text", truncation=True, max_length=2048, return_tensors="pt")
125
+ with torch.no_grad():
126
+ h = enc(**b).last_hidden_state; m = b['attention_mask'].unsqueeze(-1).float()
127
+ p = ((h*m).sum(1)/m.sum(1).clamp(min=1e-9) @ head['weight'].T + head['bias']).sigmoid()[0]
128
+ for s, i in zip(*p.topk(10)):
129
+ if s > 0.9: # concept threshold; MT 0.80, DO 0.70
130
+ print(names.get(str(mlb.classes_[i]), mlb.classes_[i]), float(s))
131
  ```
 
132
 
133
+ ## Authors
134
 
135
+ Original EuroVoc classifier (English RoBERTa): Sébastien Campion, Andreas Papagiannis (European Parliament).
136
 
137
+ Multilingual mmBERT version: Harun Kalkanci, Andreas Papagiannis (European Parliament).
architecture.png DELETED

Git LFS Details

  • SHA256: b1913dd26f85243cbb6cec67f771627d6729aa453d77b09a469f64abd29f0913
  • Pointer size: 131 Bytes
  • Size of remote file: 352 kB
classifier.pt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9f78c9041f6bdf2808fc704a14d7162791d4219e2ed6dc21312d784cf2120f1a
3
- size 20555709
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71c71fab4d96aa54f88d1f1be6c9e11d2c7388c10caff891d2bf61db6f21268b
3
+ size 21724541
config.json CHANGED
@@ -1,26 +1,78 @@
1
  {
2
  "architectures": [
3
- "RobertaModel"
4
  ],
5
- "attention_probs_dropout_prob": 0.1,
6
- "bos_token_id": 0,
7
- "classifier_dropout": null,
8
- "eos_token_id": 2,
9
- "hidden_act": "gelu",
10
- "hidden_dropout_prob": 0.1,
 
 
 
 
 
 
 
 
 
 
11
  "hidden_size": 768,
 
12
  "initializer_range": 0.02,
13
- "intermediate_size": 3072,
14
  "layer_norm_eps": 1e-05,
15
- "max_position_embeddings": 514,
16
- "model_type": "roberta",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  "num_attention_heads": 12,
18
- "num_hidden_layers": 12,
19
- "pad_token_id": 1,
20
- "position_embedding_type": "absolute",
21
- "torch_dtype": "float32",
22
- "transformers_version": "4.52.4",
23
- "type_vocab_size": 1,
24
- "use_cache": true,
25
- "vocab_size": 50265
 
 
 
 
 
 
 
 
 
 
 
26
  }
 
1
  {
2
  "architectures": [
3
+ "ModernBertModel"
4
  ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 2,
8
+ "classifier_activation": "gelu",
9
+ "classifier_bias": false,
10
+ "classifier_dropout": 0.0,
11
+ "classifier_pooling": "mean",
12
+ "cls_token_id": 1,
13
+ "decoder_bias": true,
14
+ "deterministic_flash_attn": false,
15
+ "dtype": "float32",
16
+ "embedding_dropout": 0.0,
17
+ "eos_token_id": 1,
18
+ "global_attn_every_n_layers": 3,
19
+ "gradient_checkpointing": false,
20
+ "hidden_activation": "gelu",
21
  "hidden_size": 768,
22
+ "initializer_cutoff_factor": 2.0,
23
  "initializer_range": 0.02,
24
+ "intermediate_size": 1152,
25
  "layer_norm_eps": 1e-05,
26
+ "layer_types": [
27
+ "full_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "full_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "full_attention"
49
+ ],
50
+ "local_attention": 128,
51
+ "mask_token_id": 4,
52
+ "max_position_embeddings": 8192,
53
+ "mlp_bias": false,
54
+ "mlp_dropout": 0.0,
55
+ "model_type": "modernbert",
56
+ "norm_bias": false,
57
+ "norm_eps": 1e-05,
58
  "num_attention_heads": 12,
59
+ "num_hidden_layers": 22,
60
+ "pad_token_id": 0,
61
+ "position_embedding_type": "sans_pos",
62
+ "rope_parameters": {
63
+ "full_attention": {
64
+ "rope_theta": 160000,
65
+ "rope_type": "default"
66
+ },
67
+ "sliding_attention": {
68
+ "rope_theta": 160000,
69
+ "rope_type": "default"
70
+ }
71
+ },
72
+ "sep_token_id": 1,
73
+ "sparse_pred_ignore_index": -100,
74
+ "sparse_prediction": false,
75
+ "tie_word_embeddings": true,
76
+ "transformers_version": "5.11.0",
77
+ "vocab_size": 256000
78
  }
eurovoc.py CHANGED
@@ -1,5 +1,5 @@
1
  import torch
2
- from torch.utils.data import Dataset, DataLoader, IterableDataset
3
  import numpy as np
4
  import pytorch_lightning as pl
5
  import torch.nn as nn
@@ -7,6 +7,7 @@ import torch
7
  from transformers import BertTokenizerFast as BertTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModel
8
  import json
9
  import random
 
10
  from collections import Counter
11
  from tqdm.auto import tqdm
12
  import gzip
@@ -88,7 +89,7 @@ def get_file_label_stats(jsonl_files):
88
  for line in f:
89
  try:
90
  record = json.loads(line)
91
- eurovoc_ids = record.get('eurovoc_ids', [])
92
  label_counts.update(eurovoc_ids)
93
  total_records += 1
94
  except Exception as e:
@@ -220,7 +221,7 @@ class EurovocDataset(Dataset):
220
  text = self.text[index][0]
221
  labels = self.labels[index]
222
 
223
- encoding = self.tokenizer.encode_plus(
224
  text,
225
  add_special_tokens=True,
226
  max_length=self.max_token_len,
@@ -244,48 +245,93 @@ class StreamingEurovocDataset(IterableDataset):
244
  Streaming dataset that doesn't load everything into memory.
245
  Processes one record at a time from disk.
246
  """
247
- def __init__(self, jsonl_files, mlb, tokenizer, max_token_len=512, split='train'):
 
248
  self.jsonl_files = jsonl_files
249
  self.mlb = mlb
250
  self.tokenizer = tokenizer
251
  self.max_token_len = max_token_len
 
252
  self.split = split
 
 
 
 
 
253
 
254
  def __iter__(self):
255
- dataset = load_dataset(
256
- 'json',
257
- data_files=self.jsonl_files,
258
- streaming=True,
259
- split='train'
260
- )
261
-
262
- for record in dataset:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  text = record.get('text')
264
- eurovoc_ids = record.get('eurovoc_ids', [])
265
-
266
  # Skip invalid records
267
  if not text or not eurovoc_ids:
268
  continue
269
 
270
  # Convert concepts to binary labels
271
  labels = self.mlb.transform([eurovoc_ids])[0]
 
272
 
273
- # Tokenize
274
- encoding = self.tokenizer.encode_plus(
 
 
275
  text,
276
  add_special_tokens=True,
277
  max_length=self.max_token_len,
278
- return_token_type_ids=False,
279
- padding="max_length",
280
  truncation=True,
 
 
 
 
281
  return_attention_mask=True,
282
  return_tensors='pt',
283
  )
284
-
 
285
  yield {
286
- 'input_ids': encoding["input_ids"].flatten(),
287
- 'attention_mask': encoding["attention_mask"].flatten(),
288
- 'labels': torch.FloatTensor(labels)
 
289
  }
290
 
291
 
@@ -392,8 +438,8 @@ class StreamingEurovocDataModule(pl.LightningDataModule):
392
  Supports both random and smart (stratified) file splitting.
393
  Can load pre-computed splits from config file.
394
  """
395
- def __init__(self, bert_model_name, all_jsonl_files, mlb,
396
- batch_size=64, max_token_len=512,
397
  train_ratio=0.92, rare_threshold=0.005,
398
  split_strategy='smart',
399
  split_config_path="../eurovoc_data/train_val_split_config.json",
@@ -416,7 +462,9 @@ class StreamingEurovocDataModule(pl.LightningDataModule):
416
  self.mlb = mlb
417
  self.tokenizer = AutoTokenizer.from_pretrained(bert_model_name)
418
  self.max_token_len = max_token_len
419
-
 
 
420
  # Option 1: Load from existing config
421
  if split_config_path and os.path.exists(split_config_path):
422
  print(f"Loading split from existing config: {split_config_path}")
@@ -462,38 +510,72 @@ class StreamingEurovocDataModule(pl.LightningDataModule):
462
  self.train_files,
463
  self.mlb,
464
  self.tokenizer,
465
- self.max_token_len
 
 
466
  )
467
-
 
468
  self.val_dataset = StreamingEurovocDataset(
469
  self.val_files,
470
  self.mlb,
471
  self.tokenizer,
472
- self.max_token_len
 
473
  )
474
 
475
  def train_dataloader(self):
476
  return DataLoader(
477
  self.train_dataset,
478
  batch_size=self.batch_size,
479
- num_workers=4,
480
- pin_memory=True
 
481
  )
482
-
483
  def val_dataloader(self):
484
  return DataLoader(
485
  self.val_dataset,
486
  batch_size=self.batch_size,
487
- num_workers=4,
488
- pin_memory=True
 
489
  )
490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
 
492
  class EurovocTagger(pl.LightningModule):
493
 
494
  def __init__(self, bert_model_name, n_classes, lr=2e-5, eps=1e-8):
495
  super().__init__()
496
  self.bert = AutoModel.from_pretrained(bert_model_name)
 
 
 
497
  self.dropout = nn.Dropout(p=0.2)
498
  self.classifier1 = nn.Linear(self.bert.config.hidden_size, n_classes)
499
  self.criterion = nn.BCELoss()
@@ -523,7 +605,7 @@ class EurovocTagger(pl.LightningModule):
523
  attention_mask = batch["attention_mask"]
524
  labels = batch["labels"]
525
  loss, outputs = self(input_ids, attention_mask, labels)
526
- self.log("val_loss", loss, prog_bar=True, logger=True)
527
  return loss
528
 
529
  def test_step(self, batch, batch_idx):
@@ -539,54 +621,167 @@ class EurovocTagger(pl.LightningModule):
539
  return torch.optim.AdamW(self.parameters(), lr=self.lr, eps=self.eps)
540
 
541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  class EurovocTaggerBCELogit(pl.LightningModule):
543
 
544
- def __init__(self, bert_model_name, n_classes, lr=2e-5, eps=1e-8):
 
545
  super().__init__()
546
- self.bert = AutoModel.from_pretrained(bert_model_name)
547
- self.dropout = nn.Dropout(p=0.2)
 
 
 
 
 
 
 
 
 
 
 
548
  self.classifier1 = nn.Linear(self.bert.config.hidden_size, n_classes)
549
- self.criterion = nn.BCEWithLogitsLoss()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  self.lr = lr
551
  self.eps = eps
552
 
553
- def forward(self, input_ids, attention_mask, labels=None):
554
- output = self.bert(input_ids, attention_mask=attention_mask)
555
- output = self.dropout(output.pooler_output)
556
- output = self.classifier1(output)
 
 
 
 
 
 
 
 
 
 
 
 
557
  loss = 0
558
  if labels is not None:
559
- loss = self.criterion(output, labels)
 
 
 
 
560
  return loss, output
561
 
562
  def training_step(self, batch, batch_idx):
563
- input_ids = batch["input_ids"]
564
- attention_mask = batch["attention_mask"]
565
- labels = batch["labels"]
566
- loss, outputs = self(input_ids, attention_mask, labels)
567
  self.log("train_loss", loss, prog_bar=True, logger=True)
568
- return {"loss": loss, "predictions": outputs, "labels": labels}
 
 
 
 
 
 
569
 
570
  def validation_step(self, batch, batch_idx):
571
- input_ids = batch["input_ids"]
572
- attention_mask = batch["attention_mask"]
573
  labels = batch["labels"]
574
- loss, outputs = self(input_ids, attention_mask, labels)
575
- self.log("val_loss", loss, prog_bar=True, logger=True)
 
 
 
 
 
 
 
 
 
 
 
576
  return loss
577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
578
  def test_step(self, batch, batch_idx):
579
- input_ids = batch["input_ids"]
580
- attention_mask = batch["attention_mask"]
581
- labels = batch["labels"]
582
- loss, outputs = self(input_ids, attention_mask, labels)
583
  self.log("test_loss", loss, prog_bar=True, logger=True)
584
  return loss
585
-
586
  def configure_optimizers(self):
587
- return torch.optim.AdamW(self.parameters(), lr=self.lr, eps=self.eps)
 
 
 
 
 
 
 
 
588
 
589
-
590
  class EurovocTaggerLoRA(pl.LightningModule):
591
 
592
  def __init__(self, bert_model_name, n_classes, n_intermediate=256, lr=2e-5, eps=1e-8, lora_r=8, lora_alpha=16, lora_dropout=0.1):
@@ -594,6 +789,9 @@ class EurovocTaggerLoRA(pl.LightningModule):
594
 
595
  # Load base BERT model
596
  self.bert = AutoModel.from_pretrained(bert_model_name)
 
 
 
597
 
598
  # Configure LoRA
599
  # Target modules: query and value projection layers in attention
@@ -668,7 +866,7 @@ class EurovocTaggerLoRA(pl.LightningModule):
668
  attention_mask = batch["attention_mask"]
669
  labels = batch["labels"]
670
  loss, outputs = self(input_ids, attention_mask, labels)
671
- self.log("val_loss", loss, prog_bar=True, logger=True)
672
  return loss
673
 
674
  def test_step(self, batch, batch_idx):
 
1
  import torch
2
+ from torch.utils.data import Dataset, DataLoader, IterableDataset, get_worker_info
3
  import numpy as np
4
  import pytorch_lightning as pl
5
  import torch.nn as nn
 
7
  from transformers import BertTokenizerFast as BertTokenizer, get_linear_schedule_with_warmup, AutoTokenizer, AutoModel
8
  import json
9
  import random
10
+ import zlib
11
  from collections import Counter
12
  from tqdm.auto import tqdm
13
  import gzip
 
89
  for line in f:
90
  try:
91
  record = json.loads(line)
92
+ eurovoc_ids = record.get('eurovoc_concepts_ids', [])
93
  label_counts.update(eurovoc_ids)
94
  total_records += 1
95
  except Exception as e:
 
221
  text = self.text[index][0]
222
  labels = self.labels[index]
223
 
224
+ encoding = self.tokenizer._encode_plus(
225
  text,
226
  add_special_tokens=True,
227
  max_length=self.max_token_len,
 
245
  Streaming dataset that doesn't load everything into memory.
246
  Processes one record at a time from disk.
247
  """
248
+ def __init__(self, jsonl_files, mlb, tokenizer, max_token_len=512,
249
+ max_chunks=1, split='train', lang_keep=1):
250
  self.jsonl_files = jsonl_files
251
  self.mlb = mlb
252
  self.tokenizer = tokenizer
253
  self.max_token_len = max_token_len
254
+ self.max_chunks = max_chunks # 1 = one seq/doc (cut at max_token_len); >1 = chunk + pool
255
  self.split = split
256
+ # lang_keep>1: keep ~1 rotating language version per doc per cycle (why: see
257
+ # LANG_SAMPLING in train_bf16_ddp.py). Hash is per record, so a doc with N copies
258
+ # gets Binomial(N, 1/lang_keep) -> heavily-translated docs still come up a bit more,
259
+ # a skew inherited from the data. To make it exact: url->copy_count, sample 1/N.
260
+ self.lang_keep = lang_keep
261
 
262
  def __iter__(self):
263
+ # Shard across both DDP ranks and dataloader workers so each
264
+ # (gpu, worker) gets a disjoint slice — no duplicated records.
265
+ rank, world = 0, 1
266
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
267
+ rank = torch.distributed.get_rank()
268
+ world = torch.distributed.get_world_size()
269
+ wi = get_worker_info()
270
+ wid, nw = (wi.id, wi.num_workers) if wi else (0, 1)
271
+ shard_id, nshards = rank * nw + wid, world * nw
272
+
273
+ def _records():
274
+ # Read gz files directly (not HF load_dataset, whose per-worker
275
+ # filelock re-resolution desyncs NCCL at epoch boundaries).
276
+ # DDP: loop forever so limit_*_batches end epochs in lockstep;
277
+ # 1 process = one pass. cycle rotates the language pick (see lang_keep).
278
+ cycle = 0
279
+ while True:
280
+ for path in self.jsonl_files:
281
+ op = gzip.open if path.endswith('.gz') else open
282
+ try:
283
+ with op(path, 'rt') as fh:
284
+ for line in fh:
285
+ try:
286
+ yield cycle, json.loads(line)
287
+ except json.JSONDecodeError:
288
+ continue
289
+ except (OSError, EOFError): # skip a corrupt/truncated file
290
+ continue
291
+ cycle += 1
292
+ if world == 1:
293
+ break
294
+
295
+ for i, (cycle, record) in enumerate(_records()):
296
+ if i % nshards != shard_id: # ← skip records not mine
297
+ continue
298
+ if self.lang_keep > 1: # one language version per doc per cycle
299
+ key = f"{record.get('url')}|{record.get('lang')}|{cycle}".encode()
300
+ if zlib.crc32(key) % self.lang_keep:
301
+ continue
302
  text = record.get('text')
303
+ eurovoc_ids = record.get('eurovoc_concepts_ids', [])
304
+
305
  # Skip invalid records
306
  if not text or not eurovoc_ids:
307
  continue
308
 
309
  # Convert concepts to binary labels
310
  labels = self.mlb.transform([eurovoc_ids])[0]
311
+ labels = torch.FloatTensor(labels).squeeze() # Ensure 1D
312
 
313
+ # Tokenize into up to max_chunks windows of max_token_len so the
314
+ # WHOLE document is seen (legal docs avg ~2k words >> 512 tokens).
315
+ # return_overflowing_tokens splits long text into multiple windows.
316
+ encoding = self.tokenizer(
317
  text,
318
  add_special_tokens=True,
319
  max_length=self.max_token_len,
 
 
320
  truncation=True,
321
+ return_overflowing_tokens=True,
322
+ stride=0,
323
+ padding="max_length",
324
+ return_token_type_ids=False,
325
  return_attention_mask=True,
326
  return_tensors='pt',
327
  )
328
+ ids = encoding["input_ids"][:self.max_chunks] # (n_chunks, L)
329
+ mask = encoding["attention_mask"][:self.max_chunks]
330
  yield {
331
+ 'input_ids': ids.long(),
332
+ 'attention_mask': mask.long(),
333
+ 'labels': labels,
334
+ 'lang': record.get('lang', 'unk'), # for per-language eval; training ignores it
335
  }
336
 
337
 
 
438
  Supports both random and smart (stratified) file splitting.
439
  Can load pre-computed splits from config file.
440
  """
441
+ def __init__(self, bert_model_name, all_jsonl_files, mlb,
442
+ batch_size=64, max_token_len=512, max_chunks=1, lang_keep=1,
443
  train_ratio=0.92, rare_threshold=0.005,
444
  split_strategy='smart',
445
  split_config_path="../eurovoc_data/train_val_split_config.json",
 
462
  self.mlb = mlb
463
  self.tokenizer = AutoTokenizer.from_pretrained(bert_model_name)
464
  self.max_token_len = max_token_len
465
+ self.max_chunks = max_chunks
466
+ self.lang_keep = lang_keep # train only; see StreamingEurovocDataset
467
+
468
  # Option 1: Load from existing config
469
  if split_config_path and os.path.exists(split_config_path):
470
  print(f"Loading split from existing config: {split_config_path}")
 
510
  self.train_files,
511
  self.mlb,
512
  self.tokenizer,
513
+ self.max_token_len,
514
+ self.max_chunks,
515
+ lang_keep=self.lang_keep,
516
  )
517
+
518
+ # val is NOT sampled: we want every language version scored (per-language eval).
519
  self.val_dataset = StreamingEurovocDataset(
520
  self.val_files,
521
  self.mlb,
522
  self.tokenizer,
523
+ self.max_token_len,
524
+ self.max_chunks,
525
  )
526
 
527
  def train_dataloader(self):
528
  return DataLoader(
529
  self.train_dataset,
530
  batch_size=self.batch_size,
531
+ num_workers=6,
532
+ pin_memory=True,
533
+ collate_fn=self._collate_fn
534
  )
535
+
536
  def val_dataloader(self):
537
  return DataLoader(
538
  self.val_dataset,
539
  batch_size=self.batch_size,
540
+ num_workers=6,
541
+ pin_memory=True,
542
+ collate_fn=self._collate_fn
543
  )
544
 
545
+ @staticmethod
546
+ def _collate_fn(batch):
547
+ """Pad the ragged chunk dim to the batch max -> (B, C, L), plus a
548
+ chunk_mask (B, C) marking real vs padding chunks."""
549
+ B = len(batch)
550
+ maxc = max(item["input_ids"].size(0) for item in batch)
551
+ L = batch[0]["input_ids"].size(1)
552
+ input_ids = torch.zeros(B, maxc, L, dtype=torch.long)
553
+ attention_mask = torch.zeros(B, maxc, L, dtype=torch.long)
554
+ chunk_mask = torch.zeros(B, maxc, dtype=torch.bool)
555
+ for i, item in enumerate(batch):
556
+ c = item["input_ids"].size(0)
557
+ input_ids[i, :c] = item["input_ids"]
558
+ attention_mask[i, :c] = item["attention_mask"]
559
+ chunk_mask[i, :c] = True
560
+ labels = torch.stack([item["labels"] for item in batch])
561
+
562
+ return {
563
+ "input_ids": input_ids,
564
+ "attention_mask": attention_mask,
565
+ "chunk_mask": chunk_mask,
566
+ "labels": labels,
567
+ "lang": [item.get("lang", "unk") for item in batch], # list[str]; eval-only
568
+ }
569
+
570
 
571
  class EurovocTagger(pl.LightningModule):
572
 
573
  def __init__(self, bert_model_name, n_classes, lr=2e-5, eps=1e-8):
574
  super().__init__()
575
  self.bert = AutoModel.from_pretrained(bert_model_name)
576
+ # Enable gradient checkpointing to save memory
577
+ if hasattr(self.bert, 'gradient_checkpointing_enable'):
578
+ self.bert.gradient_checkpointing_enable()
579
  self.dropout = nn.Dropout(p=0.2)
580
  self.classifier1 = nn.Linear(self.bert.config.hidden_size, n_classes)
581
  self.criterion = nn.BCELoss()
 
605
  attention_mask = batch["attention_mask"]
606
  labels = batch["labels"]
607
  loss, outputs = self(input_ids, attention_mask, labels)
608
+ self.log("val_loss", loss, prog_bar=True, logger=True, sync_dist=True)
609
  return loss
610
 
611
  def test_step(self, batch, batch_idx):
 
621
  return torch.optim.AdamW(self.parameters(), lr=self.lr, eps=self.eps)
622
 
623
 
624
+ def focal_loss(logits, targets, gamma):
625
+ """Multi-label focal loss (Lin et al. 2017), numerically stable via BCE-with-logits.
626
+
627
+ Scales each element's BCE by (1 - p_t)**gamma, so easy/confident elements (the flood
628
+ of easy negatives, and already-learned common labels) fade and the gradient concentrates
629
+ on the hard, rare labels. That is the tail-recall lever pos_weight only crudely approximated.
630
+ gamma=0 reduces exactly to plain BCE; no pos_weight is used (the focal term does its job).
631
+ """
632
+ bce = torch.nn.functional.binary_cross_entropy_with_logits(logits, targets, reduction="none")
633
+ p = torch.sigmoid(logits)
634
+ p_t = p * targets + (1.0 - p) * (1.0 - targets) # predicted prob of the true class
635
+ return ((1.0 - p_t) ** gamma * bce).mean()
636
+
637
+
638
+ def scale_label_init(label_emb, reference_weight):
639
+ """Fit raw label-NAME embeddings to a Linear layer's default-init distribution.
640
+
641
+ Mean-centers each hidden dim across labels (drops BERT's anisotropic component, which is
642
+ shared by every name and carries no label-discriminative signal), then rescales the whole
643
+ matrix to the std of `reference_weight` (PyTorch's Kaiming init). This preserves the
644
+ relative geometry between labels (the point of a semantic init) while keeping the first
645
+ logits in the range random init would give: unscaled mean-pooled rows are ~20x larger and
646
+ would saturate sigmoid, blowing up the opening gradients. Returns reference dtype/device.
647
+ """
648
+ x = label_emb.float()
649
+ x = x - x.mean(dim=0, keepdim=True)
650
+ x = x / (x.std() + 1e-8) * reference_weight.detach().float().std()
651
+ return x.to(dtype=reference_weight.dtype, device=reference_weight.device)
652
+
653
+
654
  class EurovocTaggerBCELogit(pl.LightningModule):
655
 
656
+ def __init__(self, bert_model_name, n_classes, lr=2e-5, eps=1e-8, pos_weight=None,
657
+ focal_gamma=0.0, label_init=None):
658
  super().__init__()
659
+ # add_pooling_layer=False: we mean-pool token states, so the pooler is unused
660
+ # (dropping it avoids DDP "unused parameters"). BERT-only kwarg; ModernBERT rejects it.
661
+ try:
662
+ self.bert = AutoModel.from_pretrained(bert_model_name, add_pooling_layer=False)
663
+ except TypeError:
664
+ self.bert = AutoModel.from_pretrained(bert_model_name)
665
+ # Gradient checkpointing: cuts activation memory so a full doc (max_chunks x
666
+ # max_token_len tokens) fits. use_reentrant=False is the DDP-safe variant.
667
+ # ~25% slower, but keeps the batch size up.
668
+ if hasattr(self.bert, 'gradient_checkpointing_enable'):
669
+ self.bert.gradient_checkpointing_enable(
670
+ gradient_checkpointing_kwargs={"use_reentrant": False})
671
+ self.dropout = nn.Dropout(p=0.3) # raised from 0.2 to curb overfitting
672
  self.classifier1 = nn.Linear(self.bert.config.hidden_size, n_classes)
673
+ # Label-semantic head (experiment #15): seed each class's classifier row with its NAME
674
+ # embedding instead of Kaiming random, so a rare label (~10 train docs) starts already
675
+ # pointing at documents whose meaning matches its name. label_init is the raw mmBERT-
676
+ # pooled name matrix (n_classes, hidden), in mlb.classes_ order; scale_label_init fits it
677
+ # to this layer's own init distribution. Absent -> ordinary random init (the v5 recipe).
678
+ if label_init is not None:
679
+ with torch.no_grad():
680
+ assert tuple(label_init.shape) == tuple(self.classifier1.weight.shape), (
681
+ f"label_init {tuple(label_init.shape)} != classifier "
682
+ f"{tuple(self.classifier1.weight.shape)}")
683
+ self.classifier1.weight.copy_(
684
+ scale_label_init(label_init, self.classifier1.weight))
685
+ # pos_weight up-weights positives to counter extreme label sparsity
686
+ # (~7k labels, ~6 positive/doc); without it BCE collapses to all-negative.
687
+ # persistent=False keeps it OUT of the checkpoint, so models loaded for
688
+ # inference (pos_weight=None) don't hit a state_dict mismatch.
689
+ if pos_weight is not None:
690
+ self.register_buffer("pos_weight",
691
+ torch.as_tensor(pos_weight, dtype=torch.float),
692
+ persistent=False)
693
+ else:
694
+ self.pos_weight = None
695
+ self.focal_gamma = focal_gamma # >0 -> focal loss (ignores pos_weight); 0 -> plain BCE
696
  self.lr = lr
697
  self.eps = eps
698
 
699
+ def forward(self, input_ids, attention_mask, labels=None, chunk_mask=None):
700
+ # input_ids/attention_mask: (B, C, L) - C chunks per document.
701
+ B, C, L = input_ids.shape
702
+ flat_am = attention_mask.view(B * C, L)
703
+ out = self.bert(input_ids.view(B * C, L), attention_mask=flat_am)
704
+ # 1) masked mean-pool tokens -> one vector per chunk
705
+ tok = flat_am.unsqueeze(-1).float()
706
+ chunk_emb = (out.last_hidden_state * tok).sum(1) / tok.sum(1).clamp(min=1e-9)
707
+ # all-pad chunks have no valid tokens -> NaN; zero them (they're masked).
708
+ chunk_emb = torch.nan_to_num(chunk_emb).view(B, C, -1)
709
+ # 2) masked mean-pool over real chunks -> one vector per document
710
+ if chunk_mask is None:
711
+ chunk_mask = torch.ones(B, C, dtype=torch.bool, device=chunk_emb.device)
712
+ cm = chunk_mask.unsqueeze(-1).float()
713
+ pooled = (chunk_emb * cm).sum(1) / cm.sum(1).clamp(min=1e-9)
714
+ output = self.classifier1(self.dropout(pooled))
715
  loss = 0
716
  if labels is not None:
717
+ if self.focal_gamma > 0:
718
+ loss = focal_loss(output, labels, self.focal_gamma)
719
+ else:
720
+ loss = torch.nn.functional.binary_cross_entropy_with_logits(
721
+ output, labels, pos_weight=self.pos_weight)
722
  return loss, output
723
 
724
  def training_step(self, batch, batch_idx):
725
+ loss, outputs = self(batch["input_ids"], batch["attention_mask"],
726
+ batch["labels"], chunk_mask=batch.get("chunk_mask"))
 
 
727
  self.log("train_loss", loss, prog_bar=True, logger=True)
728
+ return {"loss": loss, "predictions": outputs, "labels": batch["labels"]}
729
+
730
+ # Plain counters (not buffers) so adding metrics doesn't change the
731
+ # checkpoint state_dict -> resume from an older ckpt still loads.
732
+ def on_validation_epoch_start(self):
733
+ self._tp = self._fp = self._fn = 0.0 # for micro-F1 @0.5
734
+ self._pk_hits = self._pk_n = 0.0 # for precision@5
735
 
736
  def validation_step(self, batch, batch_idx):
 
 
737
  labels = batch["labels"]
738
+ loss, logits = self(batch["input_ids"], batch["attention_mask"],
739
+ labels, chunk_mask=batch.get("chunk_mask"))
740
+ self.log("val_loss", loss, prog_bar=True, logger=True, sync_dist=True)
741
+
742
+ probs = torch.sigmoid(logits)
743
+ pred, tgt = probs > 0.5, labels.bool()
744
+ self._tp += (pred & tgt).sum().item()
745
+ self._fp += (pred & ~tgt).sum().item()
746
+ self._fn += (~pred & tgt).sum().item()
747
+ k = min(5, probs.size(1))
748
+ topk = probs.topk(k, dim=1).indices
749
+ self._pk_hits += labels.gather(1, topk).sum().item()
750
+ self._pk_n += labels.size(0) * k
751
  return loss
752
 
753
+ def on_validation_epoch_end(self):
754
+ def _global(x): # sum counters across DDP ranks
755
+ t = torch.tensor(float(x), device=self.device)
756
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
757
+ torch.distributed.all_reduce(t)
758
+ return t.item()
759
+ tp, fp, fn = _global(self._tp), _global(self._fp), _global(self._fn)
760
+ hits, n = _global(self._pk_hits), _global(self._pk_n)
761
+ prec = tp / (tp + fp + 1e-9)
762
+ rec = tp / (tp + fn + 1e-9)
763
+ f1 = 2 * prec * rec / (prec + rec + 1e-9)
764
+ # values already global -> log without sync_dist
765
+ self.log("val_micro_f1", f1, prog_bar=True)
766
+ self.log("val_p_at_5", hits / (n + 1e-9), prog_bar=True)
767
+
768
  def test_step(self, batch, batch_idx):
769
+ loss, outputs = self(batch["input_ids"], batch["attention_mask"],
770
+ batch["labels"], chunk_mask=batch.get("chunk_mask"))
 
 
771
  self.log("test_loss", loss, prog_bar=True, logger=True)
772
  return loss
773
+
774
  def configure_optimizers(self):
775
+ # AdamW + weight_decay to regularize; linear warmup -> decay LR.
776
+ opt = torch.optim.AdamW(self.parameters(), lr=self.lr, eps=self.eps,
777
+ weight_decay=0.01)
778
+ total = int(self.trainer.estimated_stepping_batches) # honours limit_*/epochs/ddp
779
+ sched = get_linear_schedule_with_warmup(
780
+ opt, num_warmup_steps=int(0.05 * total), num_training_steps=total)
781
+ return {"optimizer": opt,
782
+ "lr_scheduler": {"scheduler": sched, "interval": "step"}}
783
+
784
 
 
785
  class EurovocTaggerLoRA(pl.LightningModule):
786
 
787
  def __init__(self, bert_model_name, n_classes, n_intermediate=256, lr=2e-5, eps=1e-8, lora_r=8, lora_alpha=16, lora_dropout=0.1):
 
789
 
790
  # Load base BERT model
791
  self.bert = AutoModel.from_pretrained(bert_model_name)
792
+ # Enable gradient checkpointing to save memory before applying LoRA
793
+ # if hasattr(self.bert, 'gradient_checkpointing_enable'):
794
+ # self.bert.gradient_checkpointing_enable()
795
 
796
  # Configure LoRA
797
  # Target modules: query and value projection layers in attention
 
866
  attention_mask = batch["attention_mask"]
867
  labels = batch["labels"]
868
  loss, outputs = self(input_ids, attention_mask, labels)
869
+ self.log("val_loss", loss, prog_bar=True, logger=True, sync_dist=True)
870
  return loss
871
 
872
  def test_step(self, batch, batch_idx):
inference_test.ipynb DELETED
@@ -1,386 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "id": "11ab9cd5-a6e4-416a-b44f-201e8bf8ee84",
6
- "metadata": {},
7
- "source": [
8
- "## Test inference"
9
- ]
10
- },
11
- {
12
- "cell_type": "code",
13
- "execution_count": 5,
14
- "id": "40523be3-6ec7-4cac-aa90-6b5177c0f07d",
15
- "metadata": {
16
- "tags": []
17
- },
18
- "outputs": [],
19
- "source": [
20
- "from pdfminer.high_level import extract_text"
21
- ]
22
- },
23
- {
24
- "cell_type": "code",
25
- "execution_count": 26,
26
- "id": "c0e5cc3f-5a9d-4b0f-8f7c-d46c0f79b5df",
27
- "metadata": {
28
- "tags": []
29
- },
30
- "outputs": [
31
- {
32
- "name": "stderr",
33
- "output_type": "stream",
34
- "text": [
35
- "Cannot set gray non-stroke color because /'P3954' is an invalid float value\n"
36
- ]
37
- }
38
- ],
39
- "source": [
40
- "text = extract_text(\"./example_docs_for_inference/publication_climate.pdf\")"
41
- ]
42
- },
43
- {
44
- "cell_type": "code",
45
- "execution_count": 27,
46
- "id": "120528e3-26b9-40ce-ac8c-3c30c3092d28",
47
- "metadata": {
48
- "tags": []
49
- },
50
- "outputs": [
51
- {
52
- "name": "stdout",
53
- "output_type": "stream",
54
- "text": [
55
- "ISSN 1831-9424 \n",
56
- "\n",
57
- "How to plan mitigation, adaptatio\n"
58
- ]
59
- }
60
- ],
61
- "source": [
62
- "print(text[0:50])"
63
- ]
64
- },
65
- {
66
- "cell_type": "code",
67
- "execution_count": 9,
68
- "id": "d191928f-381e-4da3-8342-1300909b52c5",
69
- "metadata": {
70
- "tags": []
71
- },
72
- "outputs": [
73
- {
74
- "name": "stderr",
75
- "output_type": "stream",
76
- "text": [
77
- "/home/mbarhdadi/projects/training/eurovoc_training_env/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
78
- " from .autonotebook import tqdm as notebook_tqdm\n"
79
- ]
80
- },
81
- {
82
- "name": "stdout",
83
- "output_type": "stream",
84
- "text": [
85
- "Model loaded. Ready to predict 6958 eurovoc labels.\n"
86
- ]
87
- }
88
- ],
89
- "source": [
90
- "import pickle\n",
91
- "from transformers import AutoTokenizer, AutoModel\n",
92
- "from eurovoc import EurovocTagger\n",
93
- "\n",
94
- "# Load MLBinarizer\n",
95
- "with open('./models_finetuned/latest/mlb.pickle', 'rb') as f:\n",
96
- " mlb = pickle.load(f)\n",
97
- "\n",
98
- "# Load tokenizer\n",
99
- "BERT_MODEL_NAME = \"nlpaueb/legal-bert-base-uncased\"\n",
100
- "tokenizer = AutoTokenizer.from_pretrained(BERT_MODEL_NAME)\n",
101
- "\n",
102
- "# Load trained model\n",
103
- "checkpoint_path = \"./models_finetuned/latest/EurovocTaggerFP32-epoch=04-val_loss=0.00.ckpt\" \n",
104
- "model = EurovocTagger.load_from_checkpoint(\n",
105
- " checkpoint_path,\n",
106
- " bert_model_name=BERT_MODEL_NAME,\n",
107
- " n_classes=len(mlb.classes_)\n",
108
- ")\n",
109
- "\n",
110
- "\n",
111
- "print(f\"Model loaded. Ready to predict {len(mlb.classes_)} eurovoc labels.\")"
112
- ]
113
- },
114
- {
115
- "cell_type": "code",
116
- "execution_count": 15,
117
- "id": "7a1fd7e6-e14d-4c24-97ae-abcd5a30ab71",
118
- "metadata": {
119
- "tags": []
120
- },
121
- "outputs": [],
122
- "source": [
123
- "def get_eurovoc_id_to_term_mapping():\n",
124
- " \"\"\"\n",
125
- " Create a mapping from eurovoc IDs to their human-readable terms.\n",
126
- " \n",
127
- " Returns:\n",
128
- " Dict mapping eurovoc_id -> term_name\n",
129
- " \"\"\"\n",
130
- " import requests\n",
131
- " import xmltodict\n",
132
- " \n",
133
- " eurovoc_id_to_term = {}\n",
134
- " \n",
135
- " response = requests.get(\n",
136
- " 'http://publications.europa.eu/resource/dataset/eurovoc',\n",
137
- " headers={\n",
138
- " 'Accept': 'application/xml',\n",
139
- " 'Accept-Language': 'en',\n",
140
- " 'User-Agent': 'Mozilla/5.0'\n",
141
- " }\n",
142
- " )\n",
143
- " \n",
144
- " data = xmltodict.parse(response.content)\n",
145
- " \n",
146
- " for term in data['xs:schema']['xs:simpleType']['xs:restriction']['xs:enumeration']:\n",
147
- " try:\n",
148
- " name = term['xs:annotation']['xs:documentation'].split('/')[0].strip()\n",
149
- " eurovoc_id = term['@value'].split(':')[1]\n",
150
- " \n",
151
- " # Map ID -> term \n",
152
- " eurovoc_id_to_term[eurovoc_id] = {\n",
153
- " 'original': name,\n",
154
- " 'lowercase': name.lower()\n",
155
- " }\n",
156
- " except (KeyError, IndexError) as e:\n",
157
- " print(f\"⚠️ Could not parse term: {term}\")\n",
158
- " \n",
159
- " print(f\"✓ Loaded {len(eurovoc_id_to_term)} eurovoc terms\")\n",
160
- " return eurovoc_id_to_term"
161
- ]
162
- },
163
- {
164
- "cell_type": "code",
165
- "execution_count": 23,
166
- "id": "d2b703ea-ca41-4353-8776-1a226f02c56b",
167
- "metadata": {
168
- "tags": []
169
- },
170
- "outputs": [
171
- {
172
- "name": "stdout",
173
- "output_type": "stream",
174
- "text": [
175
- "Loading Eurovoc terms...\n",
176
- "✓ Loaded 7488 eurovoc terms\n"
177
- ]
178
- }
179
- ],
180
- "source": [
181
- "print(\"Loading Eurovoc terms...\")\n",
182
- "eurovoc_id_to_term = get_eurovoc_id_to_term_mapping()\n"
183
- ]
184
- },
185
- {
186
- "cell_type": "code",
187
- "execution_count": 24,
188
- "id": "7a5fed81-64e8-4454-a56b-73eb50676b75",
189
- "metadata": {
190
- "tags": []
191
- },
192
- "outputs": [],
193
- "source": [
194
- "import torch\n",
195
- "import numpy as np\n",
196
- "from transformers import AutoTokenizer\n",
197
- "\n",
198
- "def predict_eurovoc_labels(text, model, mlb, tokenizer, \n",
199
- " eurovoc_id_to_term=None,\n",
200
- " max_token_len=512, \n",
201
- " threshold=0.5, \n",
202
- " top_k=10,\n",
203
- " device='cuda'):\n",
204
- " model.eval()\n",
205
- " model.to(device)\n",
206
- " \n",
207
- " # Tokenize\n",
208
- " encoding = tokenizer.encode_plus(\n",
209
- " text,\n",
210
- " add_special_tokens=True,\n",
211
- " max_length=max_token_len,\n",
212
- " return_token_type_ids=False,\n",
213
- " padding=\"max_length\",\n",
214
- " truncation=True,\n",
215
- " return_attention_mask=True,\n",
216
- " return_tensors='pt',\n",
217
- " )\n",
218
- " \n",
219
- " input_ids = encoding[\"input_ids\"].to(device)\n",
220
- " attention_mask = encoding[\"attention_mask\"].to(device)\n",
221
- " \n",
222
- " # Predict\n",
223
- " with torch.no_grad():\n",
224
- " _, outputs = model(input_ids, attention_mask)\n",
225
- " \n",
226
- "\n",
227
- " probabilities = outputs\n",
228
- " \n",
229
- " probabilities = probabilities.cpu().numpy()[0]\n",
230
- " \n",
231
- " # Helper function to enrich labels with terms\n",
232
- " def enrich_labels(label_ids, probs):\n",
233
- " \"\"\"Add human-readable terms to eurovoc IDs\"\"\"\n",
234
- " enriched = []\n",
235
- " for label_id, prob in zip(label_ids, probs):\n",
236
- " entry = {\n",
237
- " 'eurovoc_id': label_id,\n",
238
- " 'probability': float(prob)\n",
239
- " }\n",
240
- " \n",
241
- " # Add term if mapping available\n",
242
- " if eurovoc_id_to_term and label_id in eurovoc_id_to_term:\n",
243
- " entry['term'] = eurovoc_id_to_term[label_id]['original']\n",
244
- " entry['term_lower'] = eurovoc_id_to_term[label_id]['lowercase']\n",
245
- " else:\n",
246
- " entry['term'] = None\n",
247
- " entry['term_lower'] = None\n",
248
- " \n",
249
- " enriched.append(entry)\n",
250
- " \n",
251
- " return enriched\n",
252
- " \n",
253
- " # Get predictions above threshold\n",
254
- " predicted_indices = np.where(probabilities >= threshold)[0]\n",
255
- " predicted_labels = mlb.classes_[predicted_indices]\n",
256
- " predicted_probs = probabilities[predicted_indices]\n",
257
- " \n",
258
- " # Get top-k predictions\n",
259
- " top_k_indices = np.argsort(probabilities)[-top_k:][::-1]\n",
260
- " top_k_labels = mlb.classes_[top_k_indices]\n",
261
- " top_k_probs = probabilities[top_k_indices]\n",
262
- " \n",
263
- " return {\n",
264
- " 'above_threshold': {\n",
265
- " 'predictions': enrich_labels(predicted_labels, predicted_probs),\n",
266
- " 'count': len(predicted_labels)\n",
267
- " },\n",
268
- " 'top_k': {\n",
269
- " 'predictions': enrich_labels(top_k_labels, top_k_probs)\n",
270
- " }\n",
271
- " }"
272
- ]
273
- },
274
- {
275
- "cell_type": "code",
276
- "execution_count": 28,
277
- "id": "030b99aa-edc7-472a-8c7f-636a47a9cdce",
278
- "metadata": {
279
- "tags": []
280
- },
281
- "outputs": [
282
- {
283
- "name": "stdout",
284
- "output_type": "stream",
285
- "text": [
286
- "Document length: 696483 characters\n",
287
- "Truncated to: 2048 tokens (~2048 chars)\n",
288
- "\n",
289
- "Running inference...\n",
290
- "\n",
291
- "================================================================================\n",
292
- "TOP 15 PREDICTED EUROVOC LABELS (with terms)\n",
293
- "================================================================================\n",
294
- "642 | energy saving | 0.8567\n",
295
- "6700 | energy efficiency | 0.7060\n",
296
- "2281 | poverty | 0.4645\n",
297
- "5311 | user guide | 0.4198\n",
298
- "2498 | energy policy | 0.3545\n",
299
- "5482 | climate change | 0.1736\n",
300
- "754 | renewable energy | 0.1338\n",
301
- "6400 | reduction of gas emissions | 0.1321\n",
302
- "2517 | social policy | 0.1260\n",
303
- "475 | energy distribution | 0.1253\n",
304
- "5188 | information technology | 0.1087\n",
305
- "2715 | energy production | 0.1087\n",
306
- "2451 | EU policy | 0.0812\n",
307
- "4139 | serial publication | 0.0808\n",
308
- "83 | living conditions | 0.0793\n",
309
- "\n",
310
- "5 labels above threshold (0.3)\n",
311
- "\n",
312
- "================================================================================\n",
313
- "PREDICTIONS ABOVE THRESHOLD (with readable terms)\n",
314
- "================================================================================\n",
315
- "2281 | poverty | 0.4645\n",
316
- "2498 | energy policy | 0.3545\n",
317
- "5311 | user guide | 0.4198\n",
318
- "642 | energy saving | 0.8567\n",
319
- "6700 | energy efficiency | 0.7060\n"
320
- ]
321
- }
322
- ],
323
- "source": [
324
- "print(f\"Document length: {len(text)} characters\")\n",
325
- "print(f\"Truncated to: {512 * 4} tokens (~2048 chars)\\n\") \n",
326
- "\n",
327
- "print(\"Running inference...\\n\")\n",
328
- "results = predict_eurovoc_labels(\n",
329
- " text=text,\n",
330
- " model=model,\n",
331
- " mlb=mlb,\n",
332
- " tokenizer=tokenizer,\n",
333
- " eurovoc_id_to_term=eurovoc_id_to_term, # ← Pass the mapping\n",
334
- " threshold=0.3,\n",
335
- " top_k=15\n",
336
- ")\n",
337
- "print(\"=\" * 80)\n",
338
- "print(\"TOP 15 PREDICTED EUROVOC LABELS\")\n",
339
- "print(\"=\" * 80)\n",
340
- "\n",
341
- "for pred in results['top_k']['predictions']:\n",
342
- " term = pred['term'] if pred['term'] else \"(term not found)\"\n",
343
- " print(f\"{pred['eurovoc_id']:15s} | {term:45s} | {pred['probability']:.4f}\")\n",
344
- "\n",
345
- "print(f\"\\n{results['above_threshold']['count']} labels above threshold (0.3)\")\n",
346
- "\n",
347
- "print(\"\\n\" + \"=\" * 80)\n",
348
- "print(\"PREDICTIONS ABOVE THRESHOLD\")\n",
349
- "print(\"=\" * 80)\n",
350
- "\n",
351
- "for pred in results['above_threshold']['predictions']:\n",
352
- " if pred['term']: # Only show if term was found\n",
353
- " print(f\"{pred['eurovoc_id']:15s} | {pred['term']:45s} | {pred['probability']:.4f}\")"
354
- ]
355
- },
356
- {
357
- "cell_type": "code",
358
- "execution_count": null,
359
- "id": "27ebc73c-5832-4702-bc1e-dd026ebeed02",
360
- "metadata": {},
361
- "outputs": [],
362
- "source": []
363
- }
364
- ],
365
- "metadata": {
366
- "kernelspec": {
367
- "display_name": "eurovoc_training_env",
368
- "language": "python",
369
- "name": "eurovoc_training_env"
370
- },
371
- "language_info": {
372
- "codemirror_mode": {
373
- "name": "ipython",
374
- "version": 3
375
- },
376
- "file_extension": ".py",
377
- "mimetype": "text/x-python",
378
- "name": "python",
379
- "nbconvert_exporter": "python",
380
- "pygments_lexer": "ipython3",
381
- "version": "3.10.12"
382
- }
383
- },
384
- "nbformat": 4,
385
- "nbformat_minor": 5
386
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
merges.txt DELETED
The diff for this file is too large to render. See raw diff
 
metadata.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "finished_at": "2026-07-29 05:47:37",
3
+ "model": {
4
+ "base": "jhu-clsp/mmBERT-base",
5
+ "head": "linear -> BCEWithLogitsLoss (multi-label, pos_weight)",
6
+ "num_classes": 7062
7
+ },
8
+ "data": {
9
+ "train_files": 333,
10
+ "val_files": 30,
11
+ "train_records_est": 5556105,
12
+ "val_records_est": 307920,
13
+ "skipped_files": []
14
+ },
15
+ "training": {
16
+ "encoder": "mmbert",
17
+ "max_token_len": 2048,
18
+ "max_chunks": 1,
19
+ "lang_keep": 17,
20
+ "batch_size_per_gpu": 8,
21
+ "num_gpus": 3,
22
+ "accum": 9,
23
+ "effective_batch": 216,
24
+ "learning_rate": 7.5e-06,
25
+ "precision": "bf16-mixed",
26
+ "max_epochs": 11,
27
+ "train_passes_target": 4.0,
28
+ "pos_weight_cap": 40.0,
29
+ "focal_gamma": 0.0,
30
+ "label_semantic_init": true,
31
+ "limit_train_batches": 5000,
32
+ "limit_val_batches": 300,
33
+ "epochs_completed": 6,
34
+ "samples_seen": 720000,
35
+ "unique_docs_per_pass": 326829,
36
+ "steps_per_full_pass": 13617,
37
+ "full_passes_over_data": 2.2
38
+ },
39
+ "result": {
40
+ "best_checkpoint": "best-epoch=00-val_p_at_5=0.488.ckpt",
41
+ "best_val_p_at_5": 0.48822221159935
42
+ }
43
+ }
mlb.pickle CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c244b7b5ceb790fcb7c87435735cc64236c6d58b28b47eb4038341c4a35fe966
3
- size 50669
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:defe341c9fcc9f40ee756d7e599942539666db1fd372a796ae58ba566f421b68
3
+ size 51414
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:948cac15f528c74650c4f67b6b8795aeec1d1b30f8c021b359fe43b37bf9e82b
3
- size 459355280
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:083b676aeecfb73c51aeef4d3cfaf1e84e36061b2eb95b78ea59c3807f7abe34
3
+ size 1227771776
names.json ADDED
The diff for this file is too large to render. See raw diff
 
predict.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predict EuroVoc tags from the HF layout (encoder model.safetensors + classifier.pt).
2
+ Shipped into the HF repo as predict.py. Run from the model directory:
3
+
4
+ uv run python predict.py "some EU document text" # or no arg -> demo doc
5
+
6
+ Thresholds are the tuned ship operating points, not 0.5 (see MODEL_CARD.md).
7
+ """
8
+ import json
9
+ import pickle
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ from transformers import AutoModel, AutoTokenizer
15
+
16
+ HERE = Path(__file__).parent
17
+ CONCEPT_THRESHOLD = 0.9 # concept level; coarser levels use MT 0.80, DO 0.70
18
+
19
+
20
+ def load():
21
+ tok = AutoTokenizer.from_pretrained(HERE)
22
+ enc = AutoModel.from_pretrained(HERE).eval()
23
+ head = torch.load(HERE / "classifier.pt", weights_only=True)
24
+ mlb = pickle.load(open(HERE / "mlb.pickle", "rb"))
25
+ names = json.loads((HERE / "names.json").read_text())
26
+ return tok, enc, head, mlb, names
27
+
28
+
29
+ def predict(text, thresh=CONCEPT_THRESHOLD, model=None):
30
+ tok, enc, head, mlb, names = model or load() # ponytail: reloads per call; pass model= in a loop
31
+ b = tok(text, truncation=True, max_length=2048, return_tensors="pt")
32
+ with torch.no_grad():
33
+ h = enc(**b).last_hidden_state
34
+ m = b["attention_mask"].unsqueeze(-1).float()
35
+ p = ((h * m).sum(1) / m.sum(1).clamp(min=1e-9) @ head["weight"].T + head["bias"]).sigmoid()[0]
36
+ tags = [(names.get(str(mlb.classes_[i]), str(mlb.classes_[i])), float(p[i]))
37
+ for i in (p > thresh).nonzero().flatten().tolist()]
38
+ return sorted(tags, key=lambda t: -t[1])
39
+
40
+
41
+ if __name__ == "__main__":
42
+ demo = "The European Parliament adopted a regulation on renewable energy and climate policy."
43
+ text = sys.argv[1] if len(sys.argv) > 1 else demo
44
+ hits = predict(text)
45
+ print(f"{len(hits)} tags over {CONCEPT_THRESHOLD}:")
46
+ for name, score in hits:
47
+ print(f" {score:.2f} {name}")
pytorch_model.bin DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:ed711d96423ce254357983dd1da5edfb6aab1becf8abb48932f7c05c03176538
3
- size 459412231
 
 
 
 
special_tokens_map.json DELETED
@@ -1,15 +0,0 @@
1
- {
2
- "bos_token": "<s>",
3
- "cls_token": "<s>",
4
- "eos_token": "</s>",
5
- "mask_token": {
6
- "content": "<mask>",
7
- "lstrip": true,
8
- "normalized": false,
9
- "rstrip": false,
10
- "single_word": false
11
- },
12
- "pad_token": "<pad>",
13
- "sep_token": "</s>",
14
- "unk_token": "<unk>"
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tokenizer.json CHANGED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json CHANGED
@@ -1,58 +1,25 @@
1
  {
2
- "add_prefix_space": false,
3
- "added_tokens_decoder": {
4
- "0": {
5
- "content": "<s>",
6
- "lstrip": false,
7
- "normalized": true,
8
- "rstrip": false,
9
- "single_word": false,
10
- "special": true
11
- },
12
- "1": {
13
- "content": "<pad>",
14
- "lstrip": false,
15
- "normalized": true,
16
- "rstrip": false,
17
- "single_word": false,
18
- "special": true
19
- },
20
- "2": {
21
- "content": "</s>",
22
- "lstrip": false,
23
- "normalized": true,
24
- "rstrip": false,
25
- "single_word": false,
26
- "special": true
27
- },
28
- "3": {
29
- "content": "<unk>",
30
- "lstrip": false,
31
- "normalized": true,
32
- "rstrip": false,
33
- "single_word": false,
34
- "special": true
35
- },
36
- "50264": {
37
- "content": "<mask>",
38
- "lstrip": true,
39
- "normalized": false,
40
- "rstrip": false,
41
- "single_word": false,
42
- "special": true
43
- }
44
- },
45
- "bos_token": "<s>",
46
  "clean_up_tokenization_spaces": false,
47
- "cls_token": "<s>",
48
- "eos_token": "</s>",
49
- "errors": "replace",
50
- "extra_special_tokens": {},
 
 
 
 
51
  "mask_token": "<mask>",
52
- "model_max_length": 512,
 
 
 
 
53
  "pad_token": "<pad>",
54
- "sep_token": "</s>",
55
- "tokenizer_class": "RobertaTokenizer",
56
- "trim_offsets": true,
 
57
  "unk_token": "<unk>"
58
  }
 
1
  {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<bos>",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  "clean_up_tokenization_spaces": false,
5
+ "cls_token": "<bos>",
6
+ "eos_token": "<eos>",
7
+ "extra_special_tokens": [
8
+ "<start_of_turn>",
9
+ "<end_of_turn>"
10
+ ],
11
+ "is_local": false,
12
+ "local_files_only": false,
13
  "mask_token": "<mask>",
14
+ "model_input_names": [
15
+ "input_ids",
16
+ "attention_mask"
17
+ ],
18
+ "model_max_length": 8192,
19
  "pad_token": "<pad>",
20
+ "padding_side": "right",
21
+ "sep_token": "<eos>",
22
+ "spaces_between_special_tokens": false,
23
+ "tokenizer_class": "TokenizersBackend",
24
  "unk_token": "<unk>"
25
  }
train_lora_included.ipynb DELETED
@@ -1,687 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "id": "3dc740a0-1865-40da-a163-b858f29d1313",
6
- "metadata": {},
7
- "source": [
8
- "# 🇪🇺 🏷️ Eurovoc Model Training Notebook"
9
- ]
10
- },
11
- {
12
- "cell_type": "code",
13
- "execution_count": null,
14
- "id": "64a1dc4a-5bf5-46d9-9356-3958802837ac",
15
- "metadata": {},
16
- "outputs": [],
17
- "source": [
18
- "import pickle \n",
19
- "import pandas as pd\n",
20
- "from transformers import AutoTokenizer, AutoModel\n",
21
- "\n",
22
- "from datasets import load_dataset\n",
23
- "\n",
24
- "from sklearn.preprocessing import MultiLabelBinarizer\n",
25
- "import torch\n",
26
- "\n",
27
- "import pytorch_lightning as pl\n",
28
- "from pytorch_lightning.callbacks import ModelCheckpoint"
29
- ]
30
- },
31
- {
32
- "cell_type": "code",
33
- "execution_count": null,
34
- "id": "caa5dc4b-2fe3-43da-846d-a866c2224280",
35
- "metadata": {
36
- "tags": []
37
- },
38
- "outputs": [],
39
- "source": [
40
- "fixed_dir = fix_all_files(all_jsonl_files)\n",
41
- "logger.info(f\"Done! Use files from: {fixed_dir}\")"
42
- ]
43
- },
44
- {
45
- "cell_type": "markdown",
46
- "id": "6d63a920-52aa-4c73-bd2d-575e888d3d55",
47
- "metadata": {
48
- "tags": []
49
- },
50
- "source": [
51
- "### Create the MultiLabel Binarizer and save it in a file for prediction "
52
- ]
53
- },
54
- {
55
- "cell_type": "code",
56
- "execution_count": null,
57
- "id": "921fd5cd-67e7-4962-8e5e-15e055dd63b6",
58
- "metadata": {},
59
- "outputs": [],
60
- "source": [
61
- "from tqdm import tqdm\n",
62
- "\n",
63
- "\n",
64
- "import os\n",
65
- "from datetime import datetime\n",
66
- "\n",
67
- "FIXED_DIR = \"../eurovoc_data/files_fixed\"\n",
68
- "\n",
69
- "def list_all_json_files(directory=FIXED_DIR):\n",
70
- " # List all items in the directory\n",
71
- " all_items = os.listdir(directory)\n",
72
- "\n",
73
- " def extract_date_key(filename):\n",
74
- " \"\"\"\n",
75
- " Extracts a datetime object from filenames containing YYYY-MM.\n",
76
- " Handles .jsonl and .jsonl.gz.\n",
77
- " \"\"\"\n",
78
- " base = filename.split('.')[0] \n",
79
- " yyyy, mm = base.split('-') \n",
80
- " return datetime(int(yyyy), int(mm), 1)\n",
81
- "\n",
82
- "\n",
83
- " jsonl_files = [\n",
84
- " f for f in all_items\n",
85
- " if f.endswith(\".jsonl\") or f.endswith(\".jsonl.gz\")\n",
86
- " ]\n",
87
- "\n",
88
- " # Sort newest to oldest\n",
89
- " jsonl_files_sorted = sorted(\n",
90
- " jsonl_files,\n",
91
- " key=extract_date_key,\n",
92
- " reverse=True\n",
93
- " )\n",
94
- " return [os.path.join(directory, f) for f in jsonl_files_sorted]\n",
95
- "\n",
96
- "all_jsonl_files = list_all_json_files(FIXED_DIR)\n",
97
- "\n",
98
- " \n",
99
- "print(f\"Found {len(all_jsonl_files)} files to load (including compressed).\")\n",
100
- "\n",
101
- "\n",
102
- "def build_mlb_from_streaming(all_jsonl_files, output_path='../eurovoc_data/mlb.pickle'):\n",
103
- " \"\"\"\n",
104
- " Build MLBinarizer by scanning all files once to collect unique concepts.\n",
105
- " This is more memory efficient than loading everything.\n",
106
- " \"\"\"\n",
107
- " print(\"Scanning files to collect all unique eurovoc concepts...\")\n",
108
- " all_concepts = set()\n",
109
- " \n",
110
- " dataset = load_dataset(\n",
111
- " 'json',\n",
112
- " data_files=all_jsonl_files,\n",
113
- " streaming=True,\n",
114
- " split='train'\n",
115
- " )\n",
116
- " \n",
117
- " for record in tqdm(dataset, desc=\"Collecting eurovoc IDS\"):\n",
118
- " concepts = record.get('eurovoc_ids', [])\n",
119
- " if concepts:\n",
120
- " all_concepts.update(concepts)\n",
121
- " \n",
122
- " print(f\"Found {len(all_concepts)} unique eurovoc IDS\")\n",
123
- " \n",
124
- " # Create and fit MLBinarizer\n",
125
- " mlb = MultiLabelBinarizer()\n",
126
- " mlb.fit([sorted(list(all_concepts))])\n",
127
- " \n",
128
- " # Save it\n",
129
- " with open(output_path, 'wb') as f:\n",
130
- " pickle.dump(mlb, f)\n",
131
- " \n",
132
- " print(f\"Saved MLBinarizer to {output_path}\")\n",
133
- " return mlb\n",
134
- "\n"
135
- ]
136
- },
137
- {
138
- "cell_type": "code",
139
- "execution_count": null,
140
- "id": "66e1d48e-83a7-4a38-a081-b72ba679e960",
141
- "metadata": {
142
- "tags": []
143
- },
144
- "outputs": [],
145
- "source": [
146
- "build_mlb_from_streaming(all_jsonl_files)"
147
- ]
148
- },
149
- {
150
- "cell_type": "markdown",
151
- "id": "b2fd1bda-ee0e-40f2-85a6-87322a9db725",
152
- "metadata": {
153
- "tags": []
154
- },
155
- "source": [
156
- "---\n",
157
- "## 2. Load cleaned data and Split data using iterative train test \n",
158
- "\n",
159
- "## THIS ASSUMES ALL DATA IS IN 'TRAIN' OF DATASET, IF NOT ALSO LOAD IT HERE\n"
160
- ]
161
- },
162
- {
163
- "cell_type": "code",
164
- "execution_count": null,
165
- "id": "aaba16cf-a9b6-4c22-944a-2d31b8b5812d",
166
- "metadata": {
167
- "tags": []
168
- },
169
- "outputs": [],
170
- "source": [
171
- "import pickle\n",
172
- "\n",
173
- "mlb = pickle.load(open('../eurovoc_data/mlb.pickle', 'rb'))\n",
174
- "\n",
175
- "print(f\"Loaded MLBinarizer with {len(mlb.classes_)} classes\")\n",
176
- " # Show first 10\n",
177
- "print(f\"Classes: {mlb.classes_[:10]}...\") "
178
- ]
179
- },
180
- {
181
- "cell_type": "code",
182
- "execution_count": null,
183
- "id": "7f10ac21-5731-4937-8340-829d531c6116",
184
- "metadata": {},
185
- "outputs": [],
186
- "source": [
187
- "%load_ext autoreload\n",
188
- "%autoreload 2\n",
189
- "\n",
190
- "import os\n",
191
- "from datetime import datetime\n",
192
- "\n",
193
- "FIXED_DIR = \"../eurovoc_data/files_fixed\"\n",
194
- "\n",
195
- "def list_all_json_files(directory=FIXED_DIR):\n",
196
- " # List all items in the directory\n",
197
- " all_items = os.listdir(directory)\n",
198
- "\n",
199
- " def extract_date_key(filename):\n",
200
- " \"\"\"\n",
201
- " Extracts a datetime object from filenames containing YYYY-MM.\n",
202
- " Handles .jsonl and .jsonl.gz.\n",
203
- " \"\"\"\n",
204
- " base = filename.split('.')[0] \n",
205
- " yyyy, mm = base.split('-') \n",
206
- " return datetime(int(yyyy), int(mm), 1)\n",
207
- "\n",
208
- "\n",
209
- " jsonl_files = [\n",
210
- " f for f in all_items\n",
211
- " if f.endswith(\".jsonl\") or f.endswith(\".jsonl.gz\")\n",
212
- " ]\n",
213
- "\n",
214
- " # Sort newest to oldest\n",
215
- " jsonl_files_sorted = sorted(\n",
216
- " jsonl_files,\n",
217
- " key=extract_date_key,\n",
218
- " reverse=True\n",
219
- " )\n",
220
- " return [os.path.join(directory, f) for f in jsonl_files_sorted]\n",
221
- "\n",
222
- "all_jsonl_files = list_all_json_files(FIXED_DIR)\n",
223
- "\n",
224
- " \n",
225
- "print(f\"Found {len(all_jsonl_files)} files to load (including compressed).\")\n"
226
- ]
227
- },
228
- {
229
- "cell_type": "code",
230
- "execution_count": null,
231
- "id": "25ecca51-7901-448b-9d89-4ed0663b2bae",
232
- "metadata": {
233
- "tags": []
234
- },
235
- "outputs": [],
236
- "source": [
237
- "import gc\n",
238
- "gc.collect()"
239
- ]
240
- },
241
- {
242
- "cell_type": "markdown",
243
- "id": "1ff0c6b0-abcb-4424-be97-5c7bd8fb9af7",
244
- "metadata": {},
245
- "source": [
246
- "## 2.1 Model definition"
247
- ]
248
- },
249
- {
250
- "cell_type": "markdown",
251
- "id": "aaa9dc1b-1086-47d2-9b3b-20d954bda644",
252
- "metadata": {},
253
- "source": [
254
- "---\n",
255
- "## 3. Model definition and training (NORMAL)"
256
- ]
257
- },
258
- {
259
- "cell_type": "code",
260
- "execution_count": null,
261
- "id": "5f15e504-9431-4913-9016-4b0c6344a127",
262
- "metadata": {
263
- "tags": []
264
- },
265
- "outputs": [],
266
- "source": [
267
- "import wandb\n",
268
- "\n",
269
- "wandb.login() "
270
- ]
271
- },
272
- {
273
- "cell_type": "code",
274
- "execution_count": null,
275
- "id": "2f780f9d-730c-4540-ad9a-e0b60c87f147",
276
- "metadata": {
277
- "tags": []
278
- },
279
- "outputs": [],
280
- "source": [
281
- "%load_ext autoreload\n",
282
- "%autoreload 2\n",
283
- "\n",
284
- "from eurovoc import StreamingEurovocDataModule\n",
285
- "from eurovoc import EurovocTagger\n",
286
- "from pytorch_lightning.callbacks import ModelCheckpoint\n",
287
- "import pytorch_lightning as pl\n",
288
- "import torch\n",
289
- "from pytorch_lightning.callbacks import EarlyStopping\n",
290
- "import gc\n",
291
- "\n",
292
- "class MemoryMonitorCallback(pl.Callback):\n",
293
- " def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):\n",
294
- " # Log memory every 100 batches\n",
295
- " if batch_idx % 100 == 0:\n",
296
- " if torch.cuda.is_available():\n",
297
- " for i in range(torch.cuda.device_count()):\n",
298
- " allocated = torch.cuda.memory_allocated(i) / 1e9\n",
299
- " reserved = torch.cuda.memory_reserved(i) / 1e9\n",
300
- " trainer.logger.experiment.log({\n",
301
- " f\"memory/gpu_{i}_allocated_gb\": allocated,\n",
302
- " f\"memory/gpu_{i}_reserved_gb\": reserved,\n",
303
- " \"batch_idx\": batch_idx\n",
304
- " })\n",
305
- " \n",
306
- " def on_train_epoch_end(self, trainer, pl_module):\n",
307
- " # Force cleanup at end of each epoch\n",
308
- " gc.collect()\n",
309
- " torch.cuda.empty_cache()\n",
310
- " \n",
311
- " def on_validation_epoch_end(self, trainer, pl_module):\n",
312
- " # Force cleanup after validation\n",
313
- " gc.collect()\n",
314
- " torch.cuda.empty_cache()\n",
315
- " \n",
316
- " \n",
317
- "early_stop = EarlyStopping(\n",
318
- " monitor='val_loss',\n",
319
- " patience=4,\n",
320
- " mode='min'\n",
321
- ")\n",
322
- "\n",
323
- "memory_monitor = MemoryMonitorCallback()\n",
324
- "\n",
325
- "checkpoint_callback = ModelCheckpoint(\n",
326
- " monitor='val_loss',\n",
327
- " filename='EurovocTaggerFP32-{epoch:02d}-{val_loss:.2f}',\n",
328
- " mode='min',\n",
329
- ")\n"
330
- ]
331
- },
332
- {
333
- "cell_type": "code",
334
- "execution_count": null,
335
- "id": "a069d202-2e61-4148-baeb-20fbd9b7bf7b",
336
- "metadata": {
337
- "tags": []
338
- },
339
- "outputs": [],
340
- "source": [
341
- "from pytorch_lightning.loggers import WandbLogger\n",
342
- "wandb_logger = WandbLogger(\n",
343
- " project=\"EUROVOC\",\n",
344
- " name=\"EUROVOC-FP32\",\n",
345
- " log_model=True, \n",
346
- " save_dir=\"../logs\"\n",
347
- ")\n",
348
- "\n",
349
- "FIXED_DIR = \"../eurovoc_data/files_fixed\"\n",
350
- "\n",
351
- "BATCH_SIZE=58\n",
352
- "\n",
353
- "BERT_MODEL_NAME = \"nlpaueb/legal-bert-base-uncased\"\n",
354
- "all_jsonl_files = list_all_json_files(FIXED_DIR)\n",
355
- "\n",
356
- "dataloader = StreamingEurovocDataModule(BERT_MODEL_NAME, all_jsonl_files, mlb, batch_size=BATCH_SIZE)\n",
357
- "dataloader.setup()\n",
358
- "\n",
359
- "N_EPOCHS = 30\n",
360
- "LR = 5e-05\n",
361
- "\n",
362
- "model = EurovocTagger(BERT_MODEL_NAME, len(mlb.classes_), lr=LR)\n",
363
- "\n",
364
- "\n",
365
- "wandb_logger.experiment.config.update({\n",
366
- " \"bert_model\": BERT_MODEL_NAME,\n",
367
- " \"batch_size\": BATCH_SIZE,\n",
368
- " \"learning_rate\": LR,\n",
369
- " \"max_epochs\": N_EPOCHS,\n",
370
- " \"num_workers\": 3,\n",
371
- " \"num_gpus\": 4,\n",
372
- " \"precision\": \"32\",\n",
373
- " \"num_classes\": len(mlb.classes_)\n",
374
- "})\n",
375
- "\n",
376
- "\n",
377
- "\n",
378
- "if torch.cuda.is_available():\n",
379
- " torch.backends.cuda.matmul.allow_tf32 = True\n",
380
- " torch.backends.cudnn.allow_tf32 = True\n",
381
- "\n",
382
- "torch.set_float32_matmul_precision('medium')\n",
383
- "\n",
384
- "\n",
385
- "trainer = pl.Trainer(max_epochs=N_EPOCHS ,\n",
386
- " accelerator=\"gpu\",\n",
387
- " devices=4, \n",
388
- " callbacks=[checkpoint_callback, early_stop, memory_monitor],\n",
389
- " strategy=\"ddp_notebook\",\n",
390
- " logger=wandb_logger,\n",
391
- " log_every_n_steps=50,\n",
392
- " )\n",
393
- "\n",
394
- "trainer.fit(model, dataloader)"
395
- ]
396
- },
397
- {
398
- "cell_type": "markdown",
399
- "id": "29d9203e-c02b-4a76-a57c-d2e0246722c7",
400
- "metadata": {},
401
- "source": [
402
- "## Finetuning in BF16"
403
- ]
404
- },
405
- {
406
- "cell_type": "code",
407
- "execution_count": null,
408
- "id": "86734efb-0bcd-442f-976e-ea0bbdb393d6",
409
- "metadata": {
410
- "tags": []
411
- },
412
- "outputs": [],
413
- "source": [
414
- "import wandb\n",
415
- "\n",
416
- "wandb.login() "
417
- ]
418
- },
419
- {
420
- "cell_type": "code",
421
- "execution_count": null,
422
- "id": "4b609efc-e3b7-4924-96c3-59a236f52ec6",
423
- "metadata": {
424
- "tags": []
425
- },
426
- "outputs": [],
427
- "source": [
428
- "from pytorch_lightning.loggers import WandbLogger\n",
429
- "wandb_logger = WandbLogger(\n",
430
- " project=\"EUROVOC\",\n",
431
- " name=\"EUROVOC-BF16\",\n",
432
- " log_model=True, \n",
433
- " save_dir=\"../logs\"\n",
434
- ")\n"
435
- ]
436
- },
437
- {
438
- "cell_type": "code",
439
- "execution_count": null,
440
- "id": "7cab5811-0ab9-48d5-8ec4-8d835bb0d3df",
441
- "metadata": {},
442
- "outputs": [],
443
- "source": [
444
- "#%%capture output\n",
445
- "%load_ext autoreload\n",
446
- "%autoreload 2\n",
447
- "\n",
448
- "from eurovoc import StreamingEurovocDataModule\n",
449
- "from eurovoc import EurovocTaggerBCELogit, EurovocTagger\n",
450
- "from pytorch_lightning.callbacks import ModelCheckpoint\n",
451
- "import pytorch_lightning as pl\n",
452
- "import torch\n",
453
- "from pytorch_lightning.callbacks import EarlyStopping\n",
454
- "import gc\n",
455
- "\n",
456
- "class MemoryMonitorCallback(pl.Callback):\n",
457
- " def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):\n",
458
- " # Log memory every 100 batches\n",
459
- " if batch_idx % 100 == 0:\n",
460
- " if torch.cuda.is_available():\n",
461
- " for i in range(torch.cuda.device_count()):\n",
462
- " allocated = torch.cuda.memory_allocated(i) / 1e9\n",
463
- " reserved = torch.cuda.memory_reserved(i) / 1e9\n",
464
- " trainer.logger.experiment.log({\n",
465
- " f\"memory/gpu_{i}_allocated_gb\": allocated,\n",
466
- " f\"memory/gpu_{i}_reserved_gb\": reserved\n",
467
- " })\n",
468
- " \n",
469
- " def on_train_epoch_end(self, trainer, pl_module):\n",
470
- " # Force cleanup at end of each epoch\n",
471
- " gc.collect()\n",
472
- " torch.cuda.empty_cache()\n",
473
- " \n",
474
- " def on_validation_epoch_end(self, trainer, pl_module):\n",
475
- " # Force cleanup after validation\n",
476
- " gc.collect()\n",
477
- " torch.cuda.empty_cache()\n",
478
- "\n",
479
- " \n",
480
- " \n",
481
- "\n",
482
- "early_stop = EarlyStopping(\n",
483
- " monitor='val_loss',\n",
484
- " patience=4,\n",
485
- " mode='min'\n",
486
- ")\n",
487
- "\n",
488
- "memory_monitor = MemoryMonitorCallback()\n",
489
- "\n",
490
- "checkpoint_callback = ModelCheckpoint(\n",
491
- " monitor='val_loss',\n",
492
- " filename='EurovocTaggerA-{epoch:02d}-{val_loss:.2f}',\n",
493
- " mode='min',\n",
494
- ")\n",
495
- "\n",
496
- "\n",
497
- "if torch.cuda.is_available():\n",
498
- " torch.backends.cuda.matmul.allow_tf32 = True\n",
499
- " torch.backends.cudnn.allow_tf32 = True\n",
500
- "\n",
501
- "torch.set_float32_matmul_precision('medium')\n",
502
- "\n",
503
- "\n",
504
- "FIXED_DIR = \"../eurovoc_data/files_fixed\"\n",
505
- "\n",
506
- "BATCH_SIZE=74\n",
507
- "\n",
508
- "BERT_MODEL_NAME = \"nlpaueb/legal-bert-base-uncased\"\n",
509
- "all_jsonl_files = list_all_json_files(FIXED_DIR)\n",
510
- "\n",
511
- "dataloader = StreamingEurovocDataModule(BERT_MODEL_NAME, all_jsonl_files, mlb, batch_size=BATCH_SIZE)\n",
512
- "dataloader.setup()\n",
513
- "\n",
514
- "\n",
515
- "\n",
516
- "N_EPOCHS = 30\n",
517
- "LR = 5e-05\n",
518
- "\n",
519
- "BERT_MODEL_NAME = \"nlpaueb/legal-bert-base-uncased\"\n",
520
- "\n",
521
- "\n",
522
- "model = EurovocTaggerBCELogit(BERT_MODEL_NAME, len(mlb.classes_), lr=LR)\n",
523
- "\n",
524
- "\n",
525
- "\n",
526
- "wandb_logger.experiment.config.update({\n",
527
- " \"bert_model\": BERT_MODEL_NAME,\n",
528
- " \"batch_size\": BATCH_SIZE,\n",
529
- " \"learning_rate\": LR,\n",
530
- " \"max_epochs\": N_EPOCHS,\n",
531
- " \"num_workers\": 3,\n",
532
- " \"num_gpus\": 4,\n",
533
- " \"precision\": \"16\",\n",
534
- " \"num_classes\": len(mlb.classes_)\n",
535
- "})\n",
536
- "\n",
537
- "trainer = pl.Trainer(max_epochs=N_EPOCHS ,\n",
538
- " accelerator=\"gpu\",\n",
539
- " devices=4, \n",
540
- " callbacks=[checkpoint_callback, early_stop, memory_monitor],\n",
541
- " strategy=\"ddp_notebook\",\n",
542
- " accumulate_grad_batches=1,\n",
543
- " precision=16,\n",
544
- " logger=wandb_logger,\n",
545
- " log_every_n_steps=50,\n",
546
- " )\n"
547
- ]
548
- },
549
- {
550
- "cell_type": "code",
551
- "execution_count": null,
552
- "id": "6af63c61-5ecd-4207-8aaa-2a0dbd008df2",
553
- "metadata": {
554
- "tags": []
555
- },
556
- "outputs": [],
557
- "source": [
558
- "\n",
559
- "trainer.fit(model, dataloader)"
560
- ]
561
- },
562
- {
563
- "cell_type": "markdown",
564
- "id": "2e2f69c2-9d89-4468-8198-b15da16e9403",
565
- "metadata": {},
566
- "source": [
567
- "## 4. MODEL definition and training (LORA) (STILL USES OLD EUROVOC TAGGER)"
568
- ]
569
- },
570
- {
571
- "cell_type": "code",
572
- "execution_count": null,
573
- "id": "c28014b2-5ccb-45d9-8025-d05d31d77a08",
574
- "metadata": {
575
- "tags": []
576
- },
577
- "outputs": [],
578
- "source": [
579
- "from eurovoc import StreamingEurovocDataModule\n",
580
- "from eurovoc import EurovocTaggerLoRA\n",
581
- "from pytorch_lightning.callbacks import ModelCheckpoint\n",
582
- "import pytorch_lightning as pl\n",
583
- "import torch\n",
584
- "\n",
585
- "\n",
586
- "torch.set_float32_matmul_precision('medium')\n",
587
- "\n",
588
- "FIXED_DIR = \"../eurovoc_data/files_fixed\"\n",
589
- "\n",
590
- "BATCH_SIZE=94\n",
591
- "\n",
592
- "BERT_MODEL_NAME = \"nlpaueb/legal-bert-base-uncased\"\n",
593
- "\n",
594
- "\n",
595
- "all_jsonl_files = list_all_json_files(FIXED_DIR)\n",
596
- "\n",
597
- "dataloader = StreamingEurovocDataModule(BERT_MODEL_NAME, all_jsonl_files, mlb, batch_size=BATCH_SIZE)\n",
598
- "dataloader.setup()\n",
599
- "\n",
600
- "\n",
601
- "N_EPOCHS = 30\n",
602
- "LR = 5e-05\n",
603
- "\n",
604
- "# LoRA hyperparameters\n",
605
- "# Rank of LoRA matrices\n",
606
- "LORA_R = 16 \n",
607
- "# Scaling factor (usually 2 * r)\n",
608
- "LORA_ALPHA = 32 \n",
609
- "LORA_DROPOUT = 0.1\n",
610
- "\n",
611
- "# Hierarchical classifier parameter (for 6800 labels)\n",
612
- "# Bottleneck size: 768 → 256 → 6800\n",
613
- "N_INTERMEDIATE = 256 \n",
614
- "\n",
615
- "\n",
616
- "# Create LoRA model with hierarchical classifier\n",
617
- "model = EurovocTaggerLoRA(\n",
618
- " BERT_MODEL_NAME, \n",
619
- " # 6800+ labels\n",
620
- " len(mlb.classes_),\n",
621
- " # Bottleneck size\n",
622
- " n_intermediate=N_INTERMEDIATE, \n",
623
- " lr=LR,\n",
624
- " lora_r=LORA_R,\n",
625
- " lora_alpha=LORA_ALPHA,\n",
626
- " lora_dropout=LORA_DROPOUT\n",
627
- ")\n",
628
- "\n",
629
- "checkpoint_callback = ModelCheckpoint(\n",
630
- " monitor='val_loss',\n",
631
- " filename='EurovocTaggerLoRA-6800-{epoch:02d}-{val_loss:.2f}',\n",
632
- " mode='min',\n",
633
- ")\n",
634
- "\n",
635
- "trainer = pl.Trainer(\n",
636
- " max_epochs=N_EPOCHS, \n",
637
- " accelerator=\"gpu\", \n",
638
- " devices=4, \n",
639
- " callbacks=[checkpoint_callback],\n",
640
- " strategy=\"ddp_notebook\",\n",
641
- " precision=16\n",
642
- ")\n",
643
- "\n",
644
- "print(f\"Starting LoRA training with {len(mlb.classes_)} labels...\")\n",
645
- "print(f\"Classifier architecture: 768 → {N_INTERMEDIATE} → {len(mlb.classes_)}\")\n",
646
- "trainer.fit(model, dataloader)\n",
647
- "\n",
648
- "\n",
649
- "\n"
650
- ]
651
- },
652
- {
653
- "cell_type": "code",
654
- "execution_count": null,
655
- "id": "694ad3d7-794d-4a5f-a7be-8b47e872418d",
656
- "metadata": {},
657
- "outputs": [],
658
- "source": [
659
- "# Save only the LoRA adapter \n",
660
- "model.save_lora_adapter('./eurovoc_lora_adapter')\n",
661
- "\n",
662
- "print(\"LoRA adapter saved to ./eurovoc_lora_adapter\")\n"
663
- ]
664
- }
665
- ],
666
- "metadata": {
667
- "kernelspec": {
668
- "display_name": "eurovoc_training_env",
669
- "language": "python",
670
- "name": "eurovoc_training_env"
671
- },
672
- "language_info": {
673
- "codemirror_mode": {
674
- "name": "ipython",
675
- "version": 3
676
- },
677
- "file_extension": ".py",
678
- "mimetype": "text/x-python",
679
- "name": "python",
680
- "nbconvert_exporter": "python",
681
- "pygments_lexer": "ipython3",
682
- "version": "3.10.12"
683
- }
684
- },
685
- "nbformat": 4,
686
- "nbformat_minor": 5
687
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vocab.json DELETED
The diff for this file is too large to render. See raw diff