Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • pnria/global-helper/deepgrail-linker
1 result
Select Git revision
Show changes
Commits on Source (87)
Showing
with 29528 additions and 69 deletions
SuperTagger
Utils/silver
Utils/gold
.idea
*.pt
Linker/__pycache__
Configuration/__pycache__
__pycache__
TensorBoard
train.py
import os
from configparser import ConfigParser
def read_config():
# Read configuration file
path_current_directory = os.path.dirname(__file__)
path_config_file = os.path.join(path_current_directory, 'config.ini')
config = ConfigParser()
config.read(path_config_file)
return config
[VERSION]
transformers = 4.16.2
[DATASET_PARAMS]
symbols_vocab_size = 26
atom_vocab_size = 18
max_len_sentence = 290
max_atoms_in_sentence = 868
max_atoms_in_one_type = 324
[MODEL_ENCODER]
dim_encoder = 768
[MODEL_LINKER]
nhead = 8
dim_emb_atom = 256
dim_feedforward_transformer = 512
num_layers = 3
dim_cat_out = 256
dim_intermediate_ffn = 128
dim_pre_sinkhorn_transfo = 32
dropout = 0.1
sinkhorn_iters = 5
[MODEL_TRAINING]
batch_size = 32
epoch = 30
seed_val = 42
learning_rate = 2e-3
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import torch
from utils import pad_sequence
class AtomTokenizer(object):
r"""
Tokenizer for the atoms with padding
"""
def __init__(self, atom_map, max_atoms_in_sentence):
self.atom_map = atom_map
self.max_atoms_in_sentence = max_atoms_in_sentence
self.inverse_atom_map = {v: k for k, v in self.atom_map.items()}
self.pad_token = '[PAD]'
self.pad_token_id = self.atom_map[self.pad_token]
def __len__(self):
return len(self.atom_map)
def convert_atoms_to_ids(self, atom):
r"""
Convert a atom to its id
:param atom: atom string
:return: atom id
"""
return self.atom_map[str(atom)]
def convert_sents_to_ids(self, sentences):
r"""
Convert sentences to ids
:param sentences: List of atoms in a sentence
:return: List of atoms'ids
"""
return torch.as_tensor([self.convert_atoms_to_ids(atom) for atom in sentences])
def convert_batchs_to_ids(self, batchs_sentences):
r"""
Convert a batch of sentences of atoms to the ids
:param batchs_sentences: batch of sentences atoms
:return: list of list of atoms'ids
"""
return torch.as_tensor(pad_sequence([self.convert_sents_to_ids(sents) for sents in batchs_sentences],
max_len=self.max_atoms_in_sentence, padding_value=self.pad_token_id))
def convert_ids_to_atoms(self, ids):
r"""
Translate id to atom
:param ids: atom id
:return: atom string
"""
return [self.inverse_atom_map[int(i)] for i in ids]
This diff is collapsed.
import torch
from torch import nn
import math
class PositionalEncoding(nn.Module):
def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
position = torch.arange(max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(1, max_len, d_model)
pe[0, :, 0::2] = torch.sin(position * div_term)
pe[0, :, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, x):
"""
Args:
x: Tensor, shape [batch_size, seq_len, mbedding_dim]
"""
x = x + self.pe[:, :x.size(1)]
return self.dropout(x)
from torch import logsumexp
def norm(x, dim):
return x - logsumexp(x, dim=dim, keepdim=True)
def sinkhorn_step(x):
return norm(norm(x, dim=1), dim=2)
def sinkhorn_fn_no_exp(x, tau=1, iters=3):
x = x / tau
for _ in range(iters):
x = sinkhorn_step(x)
return x
from .Linker import Linker
from .atom_map import atom_map
from .AtomTokenizer import AtomTokenizer
from .PositionalEncoding import PositionalEncoding
from .Sinkhorn import *
\ No newline at end of file
atom_map = \
{'cl_r': 0,
"pp": 1,
'n': 2,
's_ppres': 3,
's_whq': 4,
's_q': 5,
'np': 6,
's_inf': 7,
's_pass': 8,
'pp_a': 9,
'pp_par': 10,
'pp_de': 11,
'cl_y': 12,
'txt': 13,
's': 14,
's_ppart': 15,
"[SEP]":16,
'[PAD]': 17
}
atom_map_redux = {
'cl_r': 0,
'pp': 1,
'n': 2,
'np': 3,
'cl_y': 4,
'txt': 5,
's': 6
}
import torch
from torch.nn import Module
from torch.nn.functional import nll_loss
from Linker.atom_map import atom_map, atom_map_redux
class SinkhornLoss(Module):
r"""
Loss for the linker
"""
def __init__(self):
super(SinkhornLoss, self).__init__()
def forward(self, predictions, truths):
return sum(nll_loss(link.flatten(0, 1), perm.flatten(), reduction='mean', ignore_index=-1)
for link, perm in zip(predictions, truths.permute(1, 0, 2)))
def measure_accuracy(batch_true_links, axiom_links_pred):
r"""
batch_true_links : (atom_vocab_size, batch_size, max_atoms_in_one_cat) contains the index of the negative atoms
axiom_links_pred : (atom_vocab_size, batch_size, max_atoms_in_one_cat) contains the index of the negative atoms
"""
padding = -1
batch_true_links = batch_true_links.permute(1, 0, 2)
correct_links = torch.ones(axiom_links_pred.size())
correct_links[axiom_links_pred != batch_true_links] = 0
correct_links[batch_true_links == padding] = 1
num_correct_links = correct_links.sum().item()
num_masked_atoms = len(batch_true_links[batch_true_links == padding])
# diviser par nombre de links
return (num_correct_links - num_masked_atoms) / (
axiom_links_pred.size()[0] * axiom_links_pred.size()[1] * axiom_links_pred.size()[2] - num_masked_atoms)
import re
import pandas as pd
import regex
import torch
from torch.nn import Sequential, Linear, Dropout, GELU
from torch.nn import Module
from Linker.atom_map import atom_map, atom_map_redux
from utils import pad_sequence
class FFN(Module):
"Implements FFN equation."
def __init__(self, d_model, d_ff, dropout=0.1, d_out=None):
super(FFN, self).__init__()
self.ffn = Sequential(
Linear(d_model, d_ff, bias=False),
GELU(),
Dropout(dropout),
Linear(d_ff, d_out if d_out is not None else d_model, bias=False)
)
def forward(self, x):
return self.ffn(x)
################################ Regex ########################################
regex_categories_axiom_links = r'\w+\(\d+,(?:((?R))|(\w+))*,?(?:((?R))|(\w+))*\)'
regex_categories = r'\w+\(\d+,(?:((?R))|(\w+))*,?(?:((?R))|(\w+))*\)'
# region get true axiom links
def get_axiom_links(max_atoms_in_one_type, atoms_polarity, batch_axiom_links):
r"""
Args:
max_atoms_in_one_type : configuration
atoms_polarity : (batch_size, max_atoms_in_sentence)
batch_axiom_links : (batch_size, len_sentence) categories with the _i which allows linking atoms
Returns:
batch_true_links : (batch_size, atom_vocab_size, max_atoms_in_one_cat) contains the index of the negative atoms
"""
atoms_batch = get_atoms_links_batch(batch_axiom_links)
linking_plus_to_minus_all_types = []
for atom_type in list(atom_map_redux.keys()):
# filtrer sur atom_batch que ce type puis filtrer avec les indices sur atom polarity
l_polarity_plus = [[x for i, x in enumerate(atoms_batch[s_idx]) if atoms_polarity[s_idx, i]
and bool(re.match(r"" + atom_type + "(_{1}\w+)?_\d+\Z", atoms_batch[s_idx][i]))] for s_idx
in range(len(atoms_batch))]
l_polarity_minus = [[x for i, x in enumerate(atoms_batch[s_idx]) if not atoms_polarity[s_idx, i]
and bool(re.match(r"" + atom_type + "(_{1}\w+)?_\d+\Z", atoms_batch[s_idx][i]))] for s_idx
in range(len(atoms_batch))]
linking_plus_to_minus = pad_sequence(
[torch.as_tensor(
[l_polarity_minus[s_idx].index(x) if x in l_polarity_minus[s_idx] else -1
for i, x in enumerate(l_polarity_plus[s_idx])], dtype=torch.long)
for s_idx in range(len(atoms_batch))], max_len=max_atoms_in_one_type // 2,
padding_value=-1)
linking_plus_to_minus_all_types.append(linking_plus_to_minus)
return torch.stack(linking_plus_to_minus_all_types)
def category_to_atoms_axiom_links(category, categories_to_atoms):
r"""
Args:
category : str of kind AtomCat | CategoryCat(dr or dl)
categories_to_atoms : recursive list
Returns :
List of atoms inside the category in prefix order
"""
res = [bool(re.match(r'' + atom_type + "_\d+", category)) for atom_type in atom_map.keys()]
if category.startswith("GOAL:"):
word, cat = category.split(':')
return category_to_atoms_axiom_links(cat, categories_to_atoms)
elif True in res:
return [category]
else:
category_cut = regex.match(regex_categories_axiom_links, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
for cat in category_cut:
categories_to_atoms += category_to_atoms_axiom_links(cat, [])
return categories_to_atoms
def get_atoms_links_batch(category_batch):
r"""
Args:
category_batch : (batch_size, max_atoms_in_sentence) flattened categories in prefix order
Returns :
(batch_size, max_atoms_in_sentence) flattened categories in prefix order
"""
batch = []
for sentence in category_batch:
categories_to_atoms = []
for category in sentence:
if category != "let" and not category.startswith("GOAL:"):
categories_to_atoms += category_to_atoms_axiom_links(category, [])
categories_to_atoms.append("[SEP]")
elif category.startswith("GOAL:"):
categories_to_atoms = category_to_atoms_axiom_links(category, []) + categories_to_atoms
batch.append(categories_to_atoms)
return batch
print("test to create links ",
get_axiom_links(20, torch.stack([torch.as_tensor(
[True, False, True, False, False, False, True, False, True, False,
False, True, False, False, False, True, False, False, True, False,
True, False, False, True, False, False, False, False, False, False])]),
[['dr(0,np_1,n_2)', 'n_2', 'dr(0,dl(0,np_1,np_3),np_4)', 'dr(0,np_4,n_5)', 'n_6', 'dl(0,n_6,n_5)',
'dr(0,dl(0,np_3,np_7),np_8)', 'dr(0,np_8,np_9)', 'np_9', 'GOAL:np_7']]))
# endregion
# region get atoms in sentence
def category_to_atoms(category, categories_to_atoms):
r"""
Args:
category : str of kind AtomCat | CategoryCat(dr or dl)
categories_to_atoms : recursive list
Returns:
List of atoms inside the category in prefix order
"""
res = [(category == atom_type) for atom_type in atom_map.keys()]
if category.startswith("GOAL:"):
word, cat = category.split(':')
return category_to_atoms(cat, categories_to_atoms)
elif True in res:
return [category]
else:
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
for cat in category_cut:
categories_to_atoms += category_to_atoms(cat, [])
return categories_to_atoms
def get_atoms_batch(category_batch):
r"""
Args:
category_batch : (batch_size, max_atoms_in_sentence) flattened categories in prefix order
Returns:
(batch_size, max_atoms_in_sentence) flattened categories in prefix order
"""
batch = []
for sentence in category_batch:
categories_to_atoms = []
for category in sentence:
if category != "let":
categories_to_atoms += category_to_atoms(category, [])
categories_to_atoms.append("[SEP]")
batch.append(categories_to_atoms)
return batch
print(" test for get atoms in categories on ['dr(0,np,n)', 'n', 'dr(0,dl(0,np,np),np)', 'let']",
get_atoms_batch([['dr(0,np,n)', 'n', 'dr(0,dl(0,np,np),np)', 'let']]))
# endregion
# region calculate num atoms per category
def category_to_num_atoms(category, categories_to_atoms):
r"""
Args:
category : str of kind AtomCat | CategoryCat(dr or dl)
categories_to_atoms : recursive int
Returns:
List of atoms inside the category in prefix order
"""
res = [(category == atom_type) for atom_type in atom_map.keys()]
if category.startswith("GOAL:"):
word, cat = category.split(':')
return category_to_num_atoms(cat, 0)
elif category == "let":
return 0
elif True in res:
return 1
else:
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
for cat in category_cut:
categories_to_atoms += category_to_num_atoms(cat, 0)
return categories_to_atoms
def get_num_atoms_batch(category_batch, max_len_sentence):
r"""
Args:
category_batch : (batch_size, max_atoms_in_sentence) flattened categories in prefix order
max_len_sentence : max_len_sentence parameter
Returns:
(batch_size, max_atoms_in_sentence) flattened categories in prefix order
"""
batch = []
for sentence in category_batch:
num_atoms_sentence = [0]
for category in sentence:
num_atoms_in_word = category_to_num_atoms(category, 0)
# add 1 because for word we have SEP at the end
if category != "let":
num_atoms_in_word += 1
num_atoms_sentence.append(num_atoms_in_word)
batch.append(torch.as_tensor(num_atoms_sentence))
return pad_sequence(batch, max_len=max_len_sentence, padding_value=0)
print(" test for get number of atoms in categories on ['dr(0,s,np)', 'let']",
get_num_atoms_batch([["dr(0,s,np)", "let"]], 10))
# endregion
# region get polarity
def category_to_atoms_polarity(category, polarity):
r"""
Args:
category : str of kind AtomCat | CategoryCat(dr or dl)
polarity : polarity according to recursivity
Returns:
Boolean Tensor of shape max_symbols_in_word, containing 1 for pos indexes and 0 for neg indexes
"""
category_to_polarity = []
res = [(category == atom_type) for atom_type in atom_map.keys()]
# mot final
if category.startswith("GOAL:"):
word, cat = category.split(':')
res = [bool(re.match(r'' + atom_type, cat)) for atom_type in atom_map.keys()]
if True in res:
category_to_polarity.append(True)
else:
category_to_polarity += category_to_atoms_polarity(cat, True)
# le mot a une category atomique
elif True in res:
category_to_polarity.append(not polarity)
# sinon c'est une formule longue
else:
# dr = /
if category.startswith("dr"):
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
left_side, right_side = category_cut[0], category_cut[1]
# for the left side
category_to_polarity += category_to_atoms_polarity(left_side, polarity)
# for the right side : change polarity for next right formula
category_to_polarity += category_to_atoms_polarity(right_side, not polarity)
# dl = \
elif category.startswith("dl"):
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
left_side, right_side = category_cut[0], category_cut[1]
# for the left side
category_to_polarity += category_to_atoms_polarity(left_side, not polarity)
# for the right side
category_to_polarity += category_to_atoms_polarity(right_side, polarity)
# p
elif category.startswith("p"):
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
left_side, right_side = category_cut[0], category_cut[1]
# for the left side
category_to_polarity += category_to_atoms_polarity(left_side, not polarity)
# for the right side
category_to_polarity += category_to_atoms_polarity(right_side, polarity)
# box
elif category.startswith("box"):
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
category_to_polarity += category_to_atoms_polarity(category_cut[0], polarity)
# dia
elif category.startswith("dia"):
category_cut = regex.match(regex_categories, category).groups()
category_cut = [cat for cat in category_cut if cat is not None]
category_to_polarity += category_to_atoms_polarity(category_cut[0], polarity)
return category_to_polarity
def find_pos_neg_idexes(atoms_batch):
r"""
Args:
atoms_batch : (batch_size, max_atoms_in_sentence) flattened categories in prefix order
Returns:
(batch_size, max_atoms_in_sentence) flattened categories'polarities in prefix order
"""
list_batch = []
for sentence in atoms_batch:
list_atoms = []
for category in sentence:
if category == "let":
pass
else:
for at in category_to_atoms_polarity(category, True):
list_atoms.append(at)
list_atoms.append(False)
list_batch.append(list_atoms)
return list_batch
print(" test for get polarities for atoms in categories on ['dr(0,np,n)', 'n', 'dr(0,dl(0,np,np),np)', 'dr(0,np,n)', 'n', 'dl(0,n,n)', 'dr(0,dl(0,np,np),np)', 'dr(0,np,np)', 'np'] \n",
find_pos_neg_idexes([['dr(0,np,n)', 'n', 'dr(0,dl(0,np,np),np)', 'dr(0,np,n)', 'n', 'dl(0,n,n)',
'dr(0,dl(0,np,np),np)', 'dr(0,np,np)', 'np']]))
# endregion
# region get atoms and polarities with GOAL
def get_GOAL(max_len_sentence, df_axiom_links):
categories_batch = df_axiom_links["Z"]
categories_with_goal = df_axiom_links["Y"]
polarities = find_pos_neg_idexes(categories_batch)
atoms_batch = get_atoms_batch(categories_batch)
num_atoms_batch = get_num_atoms_batch(categories_batch, max_len_sentence)
for s_idx in range(len(atoms_batch)):
goal = categories_with_goal[s_idx][-1]
polarities_goal = category_to_atoms_polarity(goal, True)
goal = re.search(r"(\w+)_\d+", goal).groups()[0]
atoms = category_to_atoms(goal, [])
atoms_batch[s_idx] = atoms + atoms_batch[s_idx] # + ["[SEP]"]
polarities[s_idx] = polarities_goal + polarities[s_idx] # + False
num_atoms_batch[s_idx][0] += len(atoms) # +1
return atoms_batch, polarities, num_atoms_batch
df_axiom_links = pd.DataFrame({"Z": [['dr(0,np,n)', 'n', 'dr(0,dl(0,np,np),np)', 'dr(0,np,n)', 'n', 'dl(0,n,n)',
'dr(0,dl(0,np,np),np)', 'dr(0,np,np)', 'np']],
"Y": [['dr(0,np_1,n_2)', 'n_2', 'dr(0,dl(0,np_1,np_3),np_4)', 'dr(0,np_4,n_5)', 'n_6',
'dl(0,n_6,n_5)', 'dr(0,dl(0,np_3,np_7),np_8)', 'dr(0,np_8,np_9)', 'np_9',
'GOAL:np_7']]})
print(" test for get GOAL ", get_GOAL(10, df_axiom_links))
# endregion
# region get idx for pos and neg
def get_pos_idx(atoms_batch, atoms_polarity_batch, max_atoms_in_one_type):
pos_idx = [pad_sequence([torch.as_tensor([i for i, x in enumerate(sentence) if
bool(re.match(r"" + atom_type + "(_{1}\w+)?\Z", atoms_batch[s_idx][i])) and
atoms_polarity_batch[s_idx][i]])
for s_idx, sentence in enumerate(atoms_batch)],
max_len=max_atoms_in_one_type // 2, padding_value=-1)
for atom_type in list(atom_map_redux.keys())]
return torch.stack(pos_idx).permute(1, 0, 2)
def get_neg_idx(atoms_batch, atoms_polarity_batch, max_atoms_in_one_type):
pos_idx = [pad_sequence([torch.as_tensor([i for i, x in enumerate(sentence) if
bool(re.match(r"" + atom_type + "(_{1}\w+)?\Z", atoms_batch[s_idx][i])) and
not atoms_polarity_batch[s_idx][i]])
for s_idx, sentence in enumerate(atoms_batch)],
max_len=max_atoms_in_one_type // 2, padding_value=-1)
for atom_type in list(atom_map_redux.keys())]
return torch.stack(pos_idx).permute(1, 0, 2)
print(" test for cut into pos neg on ['dr(0,s,np)', 's']",
get_neg_idx([['s', 's', 'np', 's', 'np', '[SEP]', 's', '[SEP]']],
torch.as_tensor(
[[True, True, False, False,
True, False, False, False,
False, False,
False, False]]), 10))
# endregion
\ No newline at end of file
# DeepGrail V2
# DeepGrail Linker
This repository contains a Python implementation of a Neural Proof Net using TLGbank data.
This code was designed to work with the [DeepGrail Tagger](https://gitlab.irit.fr/pnria/global-helper/deepgrail_tagger).
In this repository we only use the embedding of the word from the tagger and the tags from the dataset, but next step is to use the prediction of the tagger for the linking step.
## Usage
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
### Installation
Python 3.9.10 **(Warning don't use Python 3.10**+**)**
Clone the project locally.
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)!
### Libraries installation
## Add your files
Run the init.sh script or install the Tagger project under SuperTagger name. And upload the tagger.pt in the directory 'models'. (You may need to modify 'model_tagger' in train.py.)
- [ ] [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:
### Structure
The structure should look like this :
```
cd existing_repo
git remote add origin https://gitlab.irit.fr/pnria/global-helper/deepgrail-v2.git
git branch -M main
git push -uf origin main
.
.
├── Configuration # Configuration
│ ├── Configuration.py # Contains the function to execute for config
│ └── config.ini # contains parameters
├── find_config.py # auto-configurate datasets parameters (max length sentence etc) according to the dataset given
├── requirements.txt # librairies needed
├── Datasets # TLGbank data with links
├── SuperTagger # The Supertagger directory (that you need to install)
│ ├── Datasets # TLGbank data
│ ├── SuperTagger # Implementation of BertForTokenClassification
│ │ ├── SuperTagger.py # Main class
│ │ └── Tagging_bert_model.py # Bert model
│ ├── predict.py # Example of prediction for supertagger
│ └── train.py # Example of train for supertagger
├── Linker # The Linker directory
│ ├── ...
│ └── Linker.py # Linker class containing the neural network
├── models
│ └── supertagger.pt # the pt file contaning the pretrained supertagger (you need to install it)
├── Output # Directory where your linker models will be savec if checkpoint=True in train
├── TensorBoard # Directory where the stats will be savec if tensorboard=True in train
└── train.py # Example of train
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.irit.fr/pnria/global-helper/deepgrail-v2/-/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/)
- [ ] [Automatically merge when pipeline succeeds](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)
### Dataset format
***
The sentences should be in a column "X", the links with '_x' postfix should be in a column "Y" and the categories in a column "Z".
For the links each atom_x goes with the one and only other atom_x in the sentence.
# Editing this README
## Training
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!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
Launch train.py, if you look at it you can give another dataset file and another tagging model.
## 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.
In train, if you use `checkpoint=True`, the model is automatically saved in a folder: Output/Training_XX-XX_XX-XX. It saves
after each epoch. Use `tensorboard=True` for log saving in folder TensorBoard. (`tensorboard --logdir=logs` for see logs)
## Name
Choose a self-explaining name for your project.
## Predicting
## 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.
For predict on your data you need to load a model (save with this code).
## 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.
## 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.
## 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.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
```
df = read_csv_pgbar(file_path,20)
texts = df['X'].tolist()
categories = df['Z'].tolist()
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
linker = Linker(tagging_model)
linker.load_weights("your/linker/path")
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.
links = linker.predict_with_categories(texts[7], categories[7])
print(links)
```
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.
The file ```postprocessing.py``` will allow you to draw the prediction. (limited sentence length otherwise it will be confusing)
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
You can also use the function ```predict_without_categories``` which only needs the sentence.
## License
For open source projects, say how it is licensed.
## Authors
## 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.
[de Pourtales Caroline](https://www.linkedin.com/in/caroline-de-pourtales/), [Rabault Julien](https://www.linkedin.com/in/julienrabault)
\ No newline at end of file
Supertagger @ 7b101512
Subproject commit 7b10151214babc2c3f1bc474eb9bec25458a8347
import itertools
import os
import re
import numpy as np
import pandas as pd
# dr = /
# dl = \
#
# def sub_tree_word(word_with_data: str):
# word = ""
# if not word_with_data.startswith("GOAL:"):
# s = word_with_data.split('|')
# word = s[0]
# tree = s[1]
# else:
# tree = word_with_data
# return word, tree
#
#
# def sub_tree_line(line_with_data: str):
# line_list = line_with_data.split()
# sentence = ""
# sub_trees = []
# for word_with_data in line_list:
# w, t = sub_tree_word(word_with_data)
# sentence += ' ' + w
# if t not in ["\\", "/", "let"] and len(t) > 0:
# sub_trees.append([t])
# """if ('ppp' in list(itertools.chain(*sub_trees))):
# print(sentence)"""
# return sentence, list(itertools.chain(*sub_trees))
#
#
# def Txt_to_csv(file_name: str, result_name):
# file = open(file_name, "r", encoding="utf8")
# text = file.readlines()
# sub = [sub_tree_line(data) for data in text]
# df = pd.DataFrame(data=sub, columns=['X', 'Y'])
# df.to_csv("../Datasets/" + result_name + "_dataset_links.csv", mode='a', index=False, header=False)
#
# def Txt_to_csv_header(file_name: str, result_name):
# file = open(file_name, "r", encoding="utf8")
# text = file.readlines()
# sub = [sub_tree_line(data) for data in text]
# df = pd.DataFrame(data=sub, columns=['X', 'Y'])
# df.to_csv("../Datasets/" + result_name + "_dataset_links.csv", index=False)
def normalize_word(orig_word):
word = orig_word.lower()
if (word is "["):
word = "("
if (word is "]"):
word = ")"
return word
def read_maxentdata(path):
allwords = []
allsuper = []
for filename in os.listdir(path):
file = os.path.join(path, filename)
with open(file, 'r', encoding="UTF8") as f:
superset = set()
words = ""
supertags = []
for line in f:
line = line.strip().split()
length = len(line)
for l in range(length):
item = line[l].split('|')
if len(item) > 1:
orig_word = item[0]
word = normalize_word(orig_word)
supertag = item[1]
superset.add(supertag)
# words += ' ' +(str(orig_word))
words += ' ' + (str(orig_word))
supertags.append(supertag)
else:
supertag = line[l]
superset.add(supertag)
supertags.append(supertag)
allwords.append(words)
allsuper.append(supertags)
words = ""
supertags = []
X = np.asarray(allwords)
Z = np.asarray(allsuper)
return X, Z
Xg,Zg = read_maxentdata("gold")
Xs,Zs= read_maxentdata("silver")
data3 = pd.read_csv('../SuperTagger/Datasets/m2_dataset.csv')
dfs = pd.DataFrame(columns = ["X", "Y"])
dfs['X'] = Xs
dfs['Y'] = Zs
print(len(dfs['X']))
rs = pd.merge(dfs, data3, on="X",how="inner").reindex(dfs.index)
rs.drop('Y1', inplace=True, axis=1)
rs.drop('Y2', inplace=True, axis=1)
# rs.drop_duplicates()
rs.to_csv("../Datasets/silver_dataset_links.csv", index=False)
dfg = pd.DataFrame(columns = ["X", "Y"])
dfg['X'] = Xg
dfg['Y'] = Zg
rg = pd.merge(dfg, data3, on="X",how="inner").reindex(dfg.index)
rg.drop('Y1', inplace=True, axis=1)
rg.drop('Y2', inplace=True, axis=1)
# rg.drop_duplicates()
rg.to_csv("../Datasets/gold_dataset_links.csv", index=False)
data1 = pd.read_csv('../Datasets/gold_dataset_links.csv')
data2 = pd.read_csv('../Datasets/silver_dataset_links.csv')
df = pd.merge(data1, data2,how='outer')
df = df.drop_duplicates(subset=['X'])
#
df[:len(df)-1].to_csv("../Datasets/goldANDsilver_dataset_links.csv", index=False)
#
# import os
# i = 0
# path = "gold"
# for filename in os.listdir(path):
# if i == 0:
# Txt_to_csv_header(os.path.join(path, filename),path)
# else :
# Txt_to_csv(os.path.join(path, filename),path)
# i+=1
#
# i = 0
# path = "silver"
# for filename in os.listdir(path):
# if i == 0:
# Txt_to_csv_header(os.path.join(path, filename),path)
# else :
# Txt_to_csv(os.path.join(path, filename),path)
# i+=1
#
# # reading csv files
# data1 = pd.read_csv('../Datasets/gold_dataset_links.csv')
# data2 = pd.read_csv('../Datasets/silver_dataset_links.csv')
# data3 = pd.read_csv('../SuperTagger/Datasets/m2_dataset.csv')
#
# # using merge function by setting how='left'
# df = pd.merge(data1, data2,how='outer')
#
# df.to_csv("../Datasets/goldANDsilver_dataset_links.csv", index=False)
#!/bin/sh
#SBATCH --job-name=Deepgrail_Linker
#SBATCH --partition=RTX6000Node
#SBATCH --gres=gpu:1
#SBATCH --mem=32000
#SBATCH --gres-flags=enforce-binding
#SBATCH --error="error_rtx1.err"
#SBATCH --output="out_rtx1.out"
module purge
module load singularity/3.0.3
srun singularity exec /logiciels/containerCollections/CUDA11/pytorch-NGC-21-03-py3.sif python "train.py"
\ No newline at end of file
import configparser
import re
import torch
from Linker.atom_map import atom_map_redux
from Linker.utils_linker import get_GOAL, get_atoms_links_batch, get_atoms_batch
from SuperTagger.SuperTagger.SuperTagger import SuperTagger
from utils import read_csv_pgbar, pad_sequence
def configurate(dataset, model_tagger, nb_sentences=1000000000):
print("#" * 20)
print("#" * 20)
print("Configuration with dataset\n")
config = configparser.ConfigParser()
config.read('Configuration/config.ini')
file_path_axiom_links = dataset
df_axiom_links = read_csv_pgbar(file_path_axiom_links, nb_sentences)
supertagger = SuperTagger()
supertagger.load_weights(model_tagger)
sentences_batch = df_axiom_links["X"].str.strip().tolist()
sentences_tokens, sentences_mask = supertagger.sent_tokenizer.fit_transform_tensors(sentences_batch)
max_len_sentence = 0
for sentence in sentences_tokens:
if len(sentence) > max_len_sentence:
max_len_sentence = len(sentence)
print("Configure parameter max len sentence to ", max_len_sentence)
config.set('DATASET_PARAMS', 'max_len_sentence', str(max_len_sentence))
atoms_batch, polarities, num_batch = get_GOAL(max_len_sentence, df_axiom_links)
max_atoms_in_sentence = 0
for sentence in atoms_batch:
if len(sentence) > max_atoms_in_sentence:
max_atoms_in_sentence = len(sentence)
print("Configure parameter max atoms in categories to", max_atoms_in_sentence)
config.set('DATASET_PARAMS', 'max_atoms_in_sentence', str(max_atoms_in_sentence))
atoms_polarity_batch = pad_sequence([torch.as_tensor(polarities[i], dtype=torch.bool) for i in range(len(polarities))],
max_len=max_atoms_in_sentence, padding_value=0)
pos_idx = [[torch.as_tensor([i for i, x in enumerate(sentence) if
bool(re.match(r"" + atom_type + "(_{1}\w+)?\Z", atoms_batch[s_idx][i]))
and atoms_polarity_batch[s_idx][i]])
for s_idx, sentence in enumerate(atoms_batch)]
for atom_type in list(atom_map_redux.keys())]
max_atoms_in_on_type = 0
for atoms_type_batch in pos_idx:
for sentence in atoms_type_batch:
length = sentence.size(0)
if length > max_atoms_in_on_type:
max_atoms_in_on_type = length
print("Configure parameter max atoms of one type in one sentence to", max_atoms_in_on_type)
config.set('DATASET_PARAMS', 'max_atoms_in_one_type', str(max_atoms_in_on_type * 2+2))
with open('Configuration/config.ini', 'w') as configfile: # save
config.write(configfile)
print("#" * 20)
print("#" * 20)
\ No newline at end of file
git clone https://gitlab.irit.fr/pnria/global-helper/deepgrail_tagger.git SuperTagger
pip install -r requirements.txt
\ No newline at end of file