Skip to content
Snippets Groups Projects
Commit a5b713f5 authored by ClemenceS's avatar ClemenceS
Browse files

add work ner experiments

parent a9fe8fa4
No related branches found
No related tags found
No related merge requests found
# ner_workflows
# Named entity recognition on Workflow data
## Description
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
This directory contains all the necessary information and scripts to reproduce the results presented in :
```
cd existing_repo
git remote add origin https://gitlab.liris.cnrs.fr/sharefair/ner_workflows.git
git branch -M main
git push -uf origin main
@misc{sebe2024extractinginformationlowresourcesetting,
title={Extracting Information in a Low-resource Setting: Case Study on Bioinformatics Workflows},
author={Clémence Sebe and Sarah Cohen-Boulakia and Olivier Ferret and Aurélie Névéol},
year={2024},
eprint={2411.19295},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2411.19295},
}
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.liris.cnrs.fr/sharefair/ner_workflows/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Before You Start
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
Before running the experiments, you need to:
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
* Download the dataset : https://doi.org/10.5281/zenodo.14879025
* Clone the Git repository : https://github.com/ClemenceS/nlstruct
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contents
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
This repository includes:
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
* A python script, `run_nlstruct.py`, to launch NER experiences whose header information must be modified (data link and model to be trained)
* A jupyter notebook, `add_voc_bioinfo.ipynb`, to integrate bioinformatics tools and binaries into models.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Licence
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
This project is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
## License
For open source projects, say how it is licensed.
## Funding
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
This work received support from the National Research Agency under the France 2030 program, with reference to ANR-22-PESN-0007.
\ No newline at end of file
%% Cell type:markdown id:cc36391f-a1b4-4958-9e2d-0034cad07759 tags:
# Add vocabulary in a nlp model
%% Cell type:markdown id:e53dd5bf-2eff-426d-aa38-f5ac3e812a53 tags:
Clémence SEBE
%% Cell type:code id:2045ee21-bf1e-4da4-9514-07d7ee270a7b tags:
``` python
import os
import re
import json
import torch
import torch.nn as nn
from transformers import AutoTokenizer, AutoModel
```
%% Cell type:markdown id:ae0a823a-f289-43b6-af29-71ca821fe6db tags:
I reuse fonctions developped in : https://github.com/LeonidasY/fast-vocabulary-transfer
%% Cell type:code id:ca110132-dc16-46ba-adf6-edd978c5bbbb tags:
``` python
def tokens_mapping(in_tokenizer, gen_tokenizer):
"""
https://github.com/LeonidasY/fast-vocabulary-transfer/blob/main/fvt/fvt.py
This method establish a mapping between each token of
the in-domain tokenizer (in_tokenizer) to one or more tokens from
the general-purpose (gen_tokenizer) tokenizer.
:param in_tokenizer: Any huggingface tokenizer
:param gen_tokenizer: Any huggingface tokenizer
:param kwargs: no kwargs
:return: A dictionary, having size of the in_tokenizer vocabulary.
Each key is the index corresponding to a token in the in-tokenizer.
Values are lists of indexes to the tokens of gen_tokenizer.
"""
gen_vocab = gen_tokenizer.get_vocab()
in_vocab = in_tokenizer.get_vocab()
ngram_vocab = in_tokenizer.ngram_vocab if hasattr(in_tokenizer, 'ngram_vocab') else {}
tokens_map = {}
for new_token, new_index in in_vocab.items():
if new_token in gen_vocab:
# if the same token exists in the old vocabulary, take its embedding
old_index = gen_vocab[new_token]
tokens_map[new_index] = [old_index]
else:
# if not, tokenize the new token using the old vocabulary
new_token = re.sub('^(##|Ġ|▁)', '', new_token)
if new_token in ngram_vocab:
token_partition = gen_tokenizer.tokenize(new_token.split(''), is_split_into_words=True)
else:
token_partition = gen_tokenizer.tokenize(new_token)
tokens_map[new_index] = [gen_vocab[old_token] for old_token in token_partition]
return tokens_map
```
%% Cell type:code id:775e5207-2f6c-4603-aaec-dbd3fe2eb614 tags:
``` python
def embeddings_assignment(tokens_map, gen_model):
"""
https://github.com/LeonidasY/fast-vocabulary-transfer/blob/main/fvt/fvt.py
Given a mapping between two tokenizers and a general-purpose model
trained on gen_tokenizer, this method produces a new embedding matrix
assigning embeddings from the gen_model.
:param tokens_map: A mapping between new and old tokens. See tokens_mapping(...)
:param gen_model: A huggingface model, e.g. bert
:param kwargs: no kwargs
:return: (2-d torch.Tensor) An embedding matrix with same size of tokens_map.
"""
gen_matrix = gen_model.get_input_embeddings().weight
in_matrix = torch.zeros(len(tokens_map), gen_matrix.shape[1])
for new_index, old_indices in tokens_map.items():
old_embedding = torch.mean(gen_matrix[old_indices], axis=0)
in_matrix[new_index] = old_embedding
return in_matrix
```
%% Cell type:code id:14d8ed15-805f-4096-b049-cfdbe21bd81f tags:
``` python
def update_model_embeddings(gen_model, in_matrix, **kwargs):
"""
https://github.com/LeonidasY/fast-vocabulary-transfer/blob/main/fvt/__init__.py
Method that replaces the embeddings of a given LM with in_matrix.
:param gen_model: An huggingface model, e.g. bert
:param in_matrix: (2-d torch.Tensor) The new embedding matrix.
:param kwargs: no kwargs
:return: A new LM model with replaced embeddings
"""
# Change the model's embedding matrix
gen_model.get_input_embeddings().weight = nn.Parameter(in_matrix)
gen_model.config.vocab_size = in_matrix.shape[0]
tie_weights = kwargs.get('tie_weights', True)
if tie_weights:
# Tie the model's weights
gen_model.tie_weights()
return gen_model
```
%% Cell type:markdown id:524f7e07-725a-4f0b-b529-ed2f12108202 tags:
### First part: list of tool names and binaries to be added
%% Cell type:code id:de4b1ae4-466f-4a4f-90a0-4a1c047daab3 tags:
``` python
which_file = "alias_bin_list.json"
with open(which_file, 'r') as mon_fichier:
json_voc = json.load(mon_fichier)
```
%% Cell type:code id:86d1d37b-fe80-4783-ba9d-278a3f994092 tags:
``` python
list_voc_to_add = []
taille_tools = {}
for sub_tool in json_voc:
for tool in sub_tool:
if len(tool) >= 5 and not "githubusercontent" in tool:
temp_tool = tool.split(".")[0]
temp_tool = temp_tool.split(":")[0]
temp_tool = ' '.join(re.sub(r'^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$', '', mot) for mot in temp_tool.split())
if len(temp_tool) >= 4 and len(temp_tool) < 30:
list_voc_to_add.append(temp_tool)
if not len(temp_tool) in taille_tools:
taille_tools[len(temp_tool)] = 1
else:
taille_tools[len(temp_tool)] += 1
"""
if len(tool) > 3 and not "githubusercontent" in tool:
list_voc_to_add.append(tool)
"""
list_voc_to_add = list(set(list_voc_to_add))
print(f"{len(list_voc_to_add)} peuvent être ajouté dans les modèles de langues")
file = open("list_voc.txt", 'w')
for t in list_voc_to_add:
file.write(f"{t}\n")
file.close()
```
%% Cell type:markdown id:d63713bc-2352-4848-97bf-937ccbfd7d09 tags:
# All in once
%% Cell type:code id:a22a39ad-8c50-4001-9462-894b8bfe7592 tags:
``` python
model_name = ["bert-base-uncased", "allenai/scibert_scivocab_uncased"]
```
%% Cell type:code id:eb05f7f2-210d-4a86-b9d0-e6d49aa24f24 tags:
``` python
for model_to_do in model_name:
print(f"\t{model_to_do}")
tokenizer_model_to_do = AutoTokenizer.from_pretrained(model_to_do)
avant = len(tokenizer_model_to_do)
print(f"Len tokenizer avant ajout : {len(tokenizer_model_to_do)}")
tokenizer_model_to_do.add_tokens(list_voc_to_add)
print(f"Len tokenizer après ajout : {len(tokenizer_model_to_do)}")
print(f'Nb voc add : {len(tokenizer_model_to_do) - avant}')
# resize token embedding
model_work_on = AutoModel.from_pretrained(model_to_do)
model_work_on.resize_token_embeddings(len(tokenizer_model_to_do))
#mapping between each token of the in-domain tokenizer (in_tokenizer) to one or more tokens from the general-purpose (gen_tokenizer) tokenizer.
tokenizer_base = AutoTokenizer.from_pretrained(model_to_do)
tokens_map = tokens_mapping(tokenizer_model_to_do, tokenizer_base)
#Given a mapping between two tokenizers and a general-purpose model trained on gen_tokenizer
in_matrix = embeddings_assignment(tokens_map, model_work_on)
#Method that replaces the embeddings of a given LM with in_matrix.
in_model = update_model_embeddings(model_work_on, in_matrix)
assert in_model.get_input_embeddings().weight.size(0) == len(tokenizer_model_to_do), "Error: embedding size does not match tokenizer size."
fold_save = "modele_" + model_to_do.replace("/", "_")
os.makedirs(fold_save, exist_ok=True)
for param in in_model.parameters():
if not param.is_contiguous():
param.data = param.data.contiguous()
#save model
in_model.save_pretrained(fold_save)
#save tokenizer
tokenizer_model_to_do.save_pretrained(fold_save)
print()
```
%% Cell type:markdown id:6837f1a0-0c98-43f8-8407-778ad078462c tags:
## Check that changes have been made
%% Cell type:code id:c2bc6896-410f-4300-b462-6d4fa9bbfee2 tags:
``` python
verif_poids = True
verif_vocab = True
for model_to_do in model_name:
print(f"\t{model_to_do}")
model_dir = "modele_" + model_to_do.replace("/", "_")
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModel.from_pretrained(model_dir)
if verif_vocab :
print(f"- Check if adding voc went well (if nothing afterwards ok)")
for token in list_voc_to_add:
if token in tokenizer.get_vocab():
# weight verification
if verif_poids :
token_id = tokenizer.convert_tokens_to_ids(token)
embedding_nouveau_token = model.get_input_embeddings().weight[token_id]
sous_tokens = tokenizer.tokenize(token, add_special_tokens=False)
sous_token_ids = tokenizer.convert_tokens_to_ids(sous_tokens)
sous_embeddings = model.get_input_embeddings().weight[sous_token_ids]
moyenne_sous_embeddings = torch.mean(sous_embeddings, dim=0)
if torch.allclose(embedding_nouveau_token, moyenne_sous_embeddings, atol=1e-6):
pass
else:
print(f"The embedding of the new token does not match the average of the sub-token : {token}")
else:
print(f"Token '{token}' is absent from the vocabulary.")
print(f"- Vérifier dimension du voc : ")
model_base = AutoModel.from_pretrained(model_to_do)
print("Base model vocabulary dimension :", model_base.get_input_embeddings().weight.size(0))
print("Modified model vocabulary dimensions :", model.get_input_embeddings().weight.size(0))
print()
```
%% Cell type:code id:e1e78860-5788-4f6f-8e8e-8edb2dd4d73a tags:
``` python
```
This diff is collapsed.
# Main file to run nlstruct
# Written by Clémence Sebe
# October 2024
from nlstruct.recipes import train_qualified_ner
import os
# List of the models
scibert_uncased = 'allenai/scibert_scivocab_cased'
bert_uncased = 'bert-base-uncased'
tab_models = [bert_uncased, scibert_uncased]
os.makedirs("models_train", exist_ok=True)
#Path of the data
# -"Ner_workflows_data/SoftCite_split"
# -"Ner_workflows_data/BioToFlow_split"
# -"Ner_workflows_data/Fusion_BioToFlow_SoftCite/with_just_conversion"
# -"Ner_workflows_data/Fusion_BioToFlow_SoftCite/with_silver"
path_data = "Ner_workflows_data/Fusion_BioToFlow_SoftCite/with_silver"
# -------------------------------------------------------------------------------------
# Vary random seeds
for graine in [1,8,22,42,100]:
# Vary train/dev splits
for i in range (1,6):
for m in tab_models:
print(f"---------------------- Iteration {i} - Model {m}")
train = True
if 'scibert_scivocab_uncased' in m:
if f'scibert_iteration{i}_seed{graine}.pt' in os.listdir("models_train"):
train = False
else:
if f'bert_iteration{i}_seed{graine}.pt' in os.listdir("models_train"):
train = False
if train:
model = train_qualified_ner(
dataset={
"train": f"{path_data}/iteration_{i}/TRAIN",
"val" : f"{path_data}/iteration_{i}/VAL",
"test" : f"Ner_workflows_data/TEST_BioToFlow"
},
finetune_bert=False,
seed=graine,
bert_name=m,
fasttext_file="",
gpus=1, #0:cpu - 1:gpu
xp_name="my-xp",
return_model=True,
max_steps = 4000,
model_to_take_encoder="None",
)
if 'scibert_scivocab_uncased' in m:
model.save_pretrained(f'models_train/scibert_iteration{i}_seed{graine}.pt')
else:
model.save_pretrained(f'models_train/bert_iteration{i}_seed{graine}.pt')
os.system('rm checkpoints/*')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment