plenz commited on
Commit
7a2e870
1 Parent(s): 93f5dc3

Upload model

Browse files
Files changed (5) hide show
  1. config.json +66 -0
  2. configuration_t5.py +145 -0
  3. modeling_t5.py +0 -0
  4. pytorch_model.bin +3 -0
  5. wrapper_functions.py +483 -0
config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "google/flan-t5-small",
3
+ "architectures": [
4
+ "T5EncoderModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_t5.T5Config",
8
+ "AutoModel": "modeling_t5.T5EncoderModel"
9
+ },
10
+ "d_ff": 1024,
11
+ "d_kv": 64,
12
+ "d_model": 512,
13
+ "decoder_start_token_id": 0,
14
+ "dense_act_fn": "gelu_new",
15
+ "dropout_rate": 0.1,
16
+ "eos_token_id": 1,
17
+ "feed_forward_proj": "gated-gelu",
18
+ "initializer_factor": 1.0,
19
+ "is_encoder_decoder": true,
20
+ "is_gated_act": true,
21
+ "layer_norm_epsilon": 1e-06,
22
+ "model_type": "glm-t5",
23
+ "n_positions": 512,
24
+ "num_decoder_layers": 8,
25
+ "num_heads": 6,
26
+ "num_layers": 8,
27
+ "output_past": true,
28
+ "pad_token_id": 0,
29
+ "relative_attention_max_distance": 128,
30
+ "relative_attention_num_additional_buckets": 3,
31
+ "relative_attention_num_buckets": 32,
32
+ "task_specific_params": {
33
+ "summarization": {
34
+ "early_stopping": true,
35
+ "length_penalty": 2.0,
36
+ "max_length": 200,
37
+ "min_length": 30,
38
+ "no_repeat_ngram_size": 3,
39
+ "num_beams": 4,
40
+ "prefix": "summarize: "
41
+ },
42
+ "translation_en_to_de": {
43
+ "early_stopping": true,
44
+ "max_length": 300,
45
+ "num_beams": 4,
46
+ "prefix": "translate English to German: "
47
+ },
48
+ "translation_en_to_fr": {
49
+ "early_stopping": true,
50
+ "max_length": 300,
51
+ "num_beams": 4,
52
+ "prefix": "translate English to French: "
53
+ },
54
+ "translation_en_to_ro": {
55
+ "early_stopping": true,
56
+ "max_length": 300,
57
+ "num_beams": 4,
58
+ "prefix": "translate English to Romanian: "
59
+ }
60
+ },
61
+ "tie_word_embeddings": false,
62
+ "torch_dtype": "float32",
63
+ "transformers_version": "4.27.3",
64
+ "use_cache": true,
65
+ "vocab_size": 32128
66
+ }
configuration_t5.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, The T5 Authors and HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ T5 model configuration"""
16
+
17
+ from typing import Mapping
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.onnx import OnnxSeq2SeqConfigWithPast
21
+ from transformers.utils import logging
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ ## FROM-T5
26
+ # T5_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ # "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
28
+ # "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json",
29
+ # "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json",
30
+ # "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json",
31
+ # "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json",
32
+ # }
33
+
34
+
35
+ class T5Config(PretrainedConfig):
36
+ r"""
37
+ This is the configuration class to store the configuration of a [`T5Model`] or a [`TFT5Model`]. It is used to
38
+ instantiate a T5 model according to the specified arguments, defining the model architecture. Instantiating a
39
+ configuration with the defaults will yield a similar configuration to that of the T5
40
+ [t5-small](https://huggingface.co/t5-small) architecture.
41
+
42
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
43
+ documentation from [`PretrainedConfig`] for more information.
44
+
45
+ Arguments:
46
+ vocab_size (`int`, *optional*, defaults to 32128):
47
+ Vocabulary size of the T5 model. Defines the number of different tokens that can be represented by the
48
+ `inputs_ids` passed when calling [`T5Model`] or [`TFT5Model`].
49
+ d_model (`int`, *optional*, defaults to 512):
50
+ Size of the encoder layers and the pooler layer.
51
+ d_kv (`int`, *optional*, defaults to 64):
52
+ Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will
53
+ be defined as `num_heads * d_kv`.
54
+ d_ff (`int`, *optional*, defaults to 2048):
55
+ Size of the intermediate feed forward layer in each `T5Block`.
56
+ num_layers (`int`, *optional*, defaults to 6):
57
+ Number of hidden layers in the Transformer encoder.
58
+ num_decoder_layers (`int`, *optional*):
59
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
60
+ num_heads (`int`, *optional*, defaults to 8):
61
+ Number of attention heads for each attention layer in the Transformer encoder.
62
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
63
+ The number of buckets to use for each attention layer.
64
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
65
+ The maximum distance of the longer sequences for the bucket separation.
66
+ dropout_rate (`float`, *optional*, defaults to 0.1):
67
+ The ratio for all dropout layers.
68
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
69
+ The epsilon used by the layer normalization layers.
70
+ initializer_factor (`float`, *optional*, defaults to 1):
71
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
72
+ testing).
73
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
74
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. T5v1.1 uses the
75
+ `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models).
78
+ """
79
+ model_type = "glm-t5"
80
+ keys_to_ignore_at_inference = ["past_key_values"]
81
+ attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_size=32128,
86
+ d_model=512,
87
+ d_kv=64,
88
+ d_ff=2048,
89
+ num_layers=6,
90
+ num_decoder_layers=None,
91
+ num_heads=8,
92
+ relative_attention_num_buckets=32,
93
+ relative_attention_max_distance=128,
94
+ dropout_rate=0.1,
95
+ layer_norm_epsilon=1e-6,
96
+ initializer_factor=1.0,
97
+ feed_forward_proj="relu",
98
+ is_encoder_decoder=True,
99
+ use_cache=True,
100
+ pad_token_id=0,
101
+ eos_token_id=1,
102
+ # GLM parameters
103
+ relative_attention_num_additional_buckets=0,
104
+ **kwargs,
105
+ ):
106
+ self.vocab_size = vocab_size
107
+ self.d_model = d_model
108
+ self.d_kv = d_kv
109
+ self.d_ff = d_ff
110
+ self.num_layers = num_layers
111
+ self.num_decoder_layers = (
112
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
113
+ ) # default = symmetry
114
+ self.num_heads = num_heads
115
+ self.relative_attention_num_buckets = relative_attention_num_buckets
116
+ self.relative_attention_max_distance = relative_attention_max_distance
117
+ self.dropout_rate = dropout_rate
118
+ self.layer_norm_epsilon = layer_norm_epsilon
119
+ self.initializer_factor = initializer_factor
120
+ self.feed_forward_proj = feed_forward_proj
121
+ self.use_cache = use_cache
122
+ self.relative_attention_num_additional_buckets = relative_attention_num_additional_buckets
123
+
124
+ act_info = self.feed_forward_proj.split("-")
125
+ self.dense_act_fn = act_info[-1]
126
+ self.is_gated_act = act_info[0] == "gated"
127
+
128
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
129
+ raise ValueError(
130
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
131
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
132
+ "'gated-gelu' or 'relu'"
133
+ )
134
+
135
+ # for backwards compatibility
136
+ if feed_forward_proj == "gated-gelu":
137
+ self.dense_act_fn = "gelu_new"
138
+
139
+ super().__init__(
140
+ pad_token_id=pad_token_id,
141
+ eos_token_id=eos_token_id,
142
+ is_encoder_decoder=is_encoder_decoder,
143
+ **kwargs,
144
+ )
145
+
modeling_t5.py ADDED
The diff for this file is too large to render. See raw diff
 
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44d2fceb8d191a3632bd63769de31e126365a572315c98ba04d257a94edf2a42
3
+ size 141355858
wrapper_functions.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from functools import partial, cache
4
+ from argparse import Namespace
5
+ from typing import List, Tuple, Dict, Union, Optional
6
+ from itertools import chain
7
+ import random
8
+ from typing import Literal
9
+
10
+ from transformers import T5Tokenizer
11
+
12
+ class Graph():
13
+ """
14
+ A graph class.
15
+ :param g: A list of tuples, where each tuple is a triple (head, r, tail).
16
+ """
17
+ def __init__(
18
+ self,
19
+ g: List[Tuple[str,str,str]] = []
20
+ ):
21
+ self.g = g
22
+ self.concepts = self.get_concepts() # list of all concepts in the graph
23
+ self.relations = self.get_relations() # list of all relations in the graph
24
+ self.relations_multiple = self.get_relations_multiple() # list of all relations in the graph, including duplicate relations
25
+
26
+ @property
27
+ def g(self) -> List[Tuple[str,str,str]]:
28
+ return self._g
29
+
30
+ @g.setter
31
+ def g(self, g: List[Tuple[str,str,str]]):
32
+ self._g = g
33
+
34
+ def num_triplets(self) -> int:
35
+ """
36
+ Get the number of triplets in the graph.
37
+ """
38
+ return len(self.g)
39
+
40
+ def get_concepts(self) -> List[str]:
41
+ """
42
+ Get the concepts in the graph.
43
+ """
44
+ concepts = list(set([triplet[i] for triplet in self.g for i in [0, 2]]))
45
+ concepts.sort() # not necessary but makes debugging easier
46
+ return concepts
47
+
48
+ def get_relations(self) -> List[str]:
49
+ """
50
+ Get the relations in the graph.
51
+ """
52
+ relations = list(set(self.get_relations_multiple()))
53
+ relations.sort() # not necessary but makes debugging easier
54
+ return relations
55
+
56
+ def get_relations_multiple(self) -> List[str]:
57
+ """
58
+ Get the relations in the graph, including duplicate relations.
59
+ """
60
+ relations = [triplet[1] for triplet in self.g]
61
+ return relations
62
+
63
+ def __str__(self):
64
+ out_str = '\n'.join([str(triplet) for triplet in self.g])
65
+ return out_str
66
+
67
+ class Data(Namespace):
68
+ def __init__(self, **kwargs):
69
+ super().__init__()
70
+ self.__dict__.update(kwargs)
71
+
72
+ def get_dummy_graph(num_triplets:int=3) -> Graph:
73
+ g = [
74
+ ("dog", "IsA", "animal"),
75
+ ("cat", "IsA", "animal"),
76
+ ("black poodle", "IsA", "dog"),
77
+ ("black cat", "IsA", "cat"),
78
+ ]
79
+ assert num_triplets <=4, "num_triplets must be <= 4"
80
+ g = g[:num_triplets]
81
+ g = Graph(g)
82
+ return g
83
+
84
+ def r2nl(r: str) -> str:
85
+ """
86
+ Convert a relation to a natural language string. Can be used to implement necessary changes in the data.
87
+ """
88
+ return r
89
+
90
+ def _get_str2tok(g:Graph, tokenizer: T5Tokenizer) -> dict[str, list[int]]:
91
+ """
92
+ Get a dictionary that maps strings to tokens.
93
+ """
94
+ # tokenize concepts and relations
95
+ c_tok = tokenizer([r2nl(c) for c in g.concepts], padding=False)['input_ids']
96
+ r_tok = tokenizer([r2nl(r) for r in g.relations], padding=False)['input_ids']
97
+
98
+ tokens = c_tok + r_tok
99
+ node_names = g.concepts + g.relations # these are not necessarily all nodes in the Levi Graph, as relations can occur more than once
100
+ assert len(tokens) == len(node_names), f"{len(tokens) = }, {len(node_names) = }"
101
+
102
+ # remove end-of-sequence token
103
+ tokens = [toks[:-1] if toks[-1] == tokenizer.eos_token_id else toks for toks in tokens]
104
+
105
+ # create a dictionary mapping concepts and relations to their tokenized forms
106
+ str2tok = {node: tok for node, tok in zip(node_names, tokens)}
107
+ str2tok['</s>'] = [tokenizer.eos_token_id]
108
+ return str2tok
109
+
110
+ def _get_graphT5_input_sequence(g:Graph, str2tok:dict, use_eos:bool) -> Tuple[list, dict]:
111
+ # get input sequence (i.e. sequence that will be fed into the model for this graph)
112
+ all_nodes = g.relations_multiple + g.concepts # list of all concepts and relations that will be in the final sequence (i.e. all nodes of the Levi Graph) # the order of nodes is first all relations (in the order that they appear in g.g), and then all concepts (in alphabetical order. though here the order is not important)
113
+
114
+ if use_eos:
115
+ all_nodes.append('</s>')
116
+
117
+ all_tokens = [str2tok[node] for node in all_nodes] # list of length #nodes, where each element is a list of token ids
118
+ indices = {node: [] for node in all_nodes} # dictionary mapping each node to its start-index and end- in the sequence. Keys are nodes, values are lists of tuples (start_index, end_index). The lists have a length of 1 for concepts and are as long as the number of occurances of the relation in the graph for relations. # WARNING: this assumes that concepts and realtions have different names. This not always the case for REBEL. For concept_indices this is fixed.
119
+ num_relation_tokens = sum([len(token) for token in all_tokens[:len(g.relations_multiple)]]) # number of tokens that are relations
120
+ num_concept_tokens = sum([len(token) for token in all_tokens[len(g.relations_multiple):len(g.relations_multiple)+len(g.concepts)]]) # number of tokens that are concepts
121
+ num_eos_tokens = 1 if use_eos else 0
122
+
123
+ is_concept = torch.tensor([False] * num_relation_tokens + [True] * num_concept_tokens + [False] * num_eos_tokens, dtype=torch.bool) # tensor of length #nodes, where each element is True if the node is a concept and False if it is a relation
124
+ index_counter = 0
125
+ assert len(all_nodes) == len(all_tokens), (all_nodes, all_tokens)
126
+
127
+ for node, token in zip(all_nodes, all_tokens):
128
+ indices[node].append((index_counter, index_counter + len(token)))
129
+ # assert is_concept[index_counter:index_counter+len(token)].all() == (node in g.concepts), f"{is_concept = }, {node = }, {g.concepts = }, {index_counter = }, {len(token) = }, {is_concept[index_counter:index_counter+len(token)] = }"
130
+ index_counter += len(token)
131
+
132
+ concept_indices = {node: [indices[node][-1]] for node in g.concepts} # [-1] and reput in list in case relations have the same name as a concept (concepts are put in last).
133
+ sequence = torch.tensor(list(chain.from_iterable(all_tokens)), dtype=torch.long)
134
+ sequence = sequence.unsqueeze(0) # add batch dimension
135
+ is_concept = is_concept.unsqueeze(0) # add batch dimension
136
+ return sequence, indices, is_concept, concept_indices
137
+
138
+ def _get_graphT5_relativeposition_sparsitymask(g:Graph, indices:dict, sequence_length:int, use_eos:bool, eos:str) -> Tuple[torch.Tensor, torch.Tensor]:
139
+ ### get relative position of each node in the sequence, as well as the sparsity mask ###
140
+ # initialize relative position matrix)
141
+ relative_position = torch.zeros(size=(sequence_length, sequence_length), dtype=torch.long)
142
+ # initialize sparsity mask
143
+ sparsity_mask = torch.zeros(size=(sequence_length, sequence_length), dtype=torch.bool)
144
+ # initialize use_additional_bucket
145
+ use_additional_bucket = torch.zeros(size=(sequence_length, sequence_length), dtype=torch.bool)
146
+
147
+ # relative positions / sparsity within each node
148
+ for start, end in chain.from_iterable(indices.values()):
149
+ relative_position[start:end, start:end] = _get_relative_position(end-start)
150
+ sparsity_mask[start:end, start:end] = True
151
+
152
+ # relative position between nodes of the same triplet
153
+ relation_counter = {relation: 0 for relation in g.relations} # dictionary mapping each relation to the number of times it has already appeared in the graph
154
+ for triplet in g.g:
155
+ pos_h = indices[triplet[0]][0] # position of head; tuple (start_index, end_index)
156
+ pos_r = indices[triplet[1]][relation_counter[triplet[1]]] # position of relation; tuple (start_index, end_index)
157
+ pos_t = indices[triplet[2]][0] # position of tail; tuple (start_index, end_index)
158
+
159
+ l_h, l_r = pos_h[1] - pos_h[0], pos_r[1] - pos_r[0] # length (i.e. number of tokens) of head and relation
160
+
161
+ # iterate over all combinations of tokens in each triplet. This implementation is not very elegant, but it is sufficiently fast.
162
+ for ih, ph in enumerate(range(pos_h[0], pos_h[1])): # iterate over all head tokens
163
+ for ir, pr in enumerate(range(pos_r[0], pos_r[1])): # iterate over all relation tokens
164
+ relative_position[ph, pr] = l_h - ih + ir
165
+ relative_position[pr, ph] = - (l_h - ih + ir)
166
+ sparsity_mask[ph, pr] = True
167
+ sparsity_mask[pr, ph] = True
168
+ for it, pt in enumerate(range(pos_t[0], pos_t[1])): # iterate over all tail tokens
169
+ relative_position[ph, pt] = l_h - ih + l_r + it
170
+ relative_position[pt, ph] = - (l_h - ih + l_r + it)
171
+ sparsity_mask[ph, pt] = True
172
+ sparsity_mask[pt, ph] = True
173
+ for ir, pr in enumerate(range(pos_r[0], pos_r[1])): # iterate over all relation tokens
174
+ for it, pt in enumerate(range(pos_t[0], pos_t[1])): # iterate over all tail tokens
175
+ relative_position[pr, pt] = l_r - ir + it
176
+ relative_position[pt, pr] = - (l_r - ir + it)
177
+ sparsity_mask[pr, pt] = True
178
+ sparsity_mask[pt, pr] = True
179
+
180
+ relation_counter[triplet[1]] += 1 # next time when that relation comes, then the next tokens will be used
181
+
182
+ if use_eos:
183
+ assert len(indices['</s>']) == 1, f"{indices['</s>'] = } should have length 1"
184
+ pos_eos = indices['</s>'][0] # position of head; tuple (start_index, end_index)
185
+ assert pos_eos[0] + 1 == pos_eos[1], pos_eos
186
+ pos_eos = pos_eos[0] # position of eos token
187
+
188
+ if eos == 'bidirectional':
189
+ relative_position[:, pos_eos] = +1e6
190
+ relative_position[pos_eos, :] = -1e6
191
+ relative_position[pos_eos, pos_eos] = 0
192
+ sparsity_mask[:, pos_eos] = True
193
+ sparsity_mask[pos_eos, :] = True
194
+ elif eos == 'unidirectional':
195
+ relative_position[:, pos_eos] = 1e6
196
+ relative_position[pos_eos, pos_eos] = 0
197
+ sparsity_mask[pos_eos, :] = False # no messages from eos to other tokens
198
+ sparsity_mask[:, pos_eos] = True
199
+ else:
200
+ raise ValueError(f'{eos = } is not a valid option.')
201
+
202
+ relative_position = relative_position.unsqueeze(0) # add batch dimension
203
+ sparsity_mask = sparsity_mask.unsqueeze(0) # add batch dimension
204
+ use_additional_bucket = use_additional_bucket.unsqueeze(0) # add batch dimension
205
+ return relative_position, sparsity_mask, use_additional_bucket
206
+
207
+ def _get_global_graphT5_relativeposition_sparsitymask(g:Graph, indices:dict, sequence_length:int, use_eos:bool, eos:str) -> Tuple[torch.Tensor, torch.Tensor]:
208
+ ### get relative position of each node in the sequence, as well as the sparsity mask ###
209
+ # initialize relative position matrix)
210
+ # relative_position = torch.ones(size=(sequence_length, sequence_length), dtype=torch.long) * 1e6 # technically should be float('inf'), but it does not matter
211
+ relative_position = torch.zeros(size=(sequence_length, sequence_length), dtype=torch.long)
212
+ # initialize sparsity mask
213
+ sparsity_mask = torch.ones(size=(sequence_length, sequence_length), dtype=torch.bool) # could switch to None, but then code has to be updated accordingly (in particular get_batch)
214
+ # initialize use_additional_bucket
215
+ use_additional_bucket = torch.ones(size=(sequence_length, sequence_length), dtype=torch.bool)
216
+
217
+ # relative positions / sparsity within each node
218
+ for start, end in chain.from_iterable(indices.values()):
219
+ relative_position[start:end, start:end] = _get_relative_position(end-start)
220
+ use_additional_bucket[start:end, start:end] = False
221
+
222
+ # relative position between nodes of the same triplet
223
+ relation_counter = {relation: 0 for relation in g.relations} # dictionary mapping each relation to the number of times it has already appeared in the graph
224
+ for triplet in g.g:
225
+ pos_h = indices[triplet[0]][0] # position of head; tuple (start_index, end_index)
226
+ pos_r = indices[triplet[1]][relation_counter[triplet[1]]] # position of relation; tuple (start_index, end_index)
227
+ pos_t = indices[triplet[2]][0] # position of tail; tuple (start_index, end_index)
228
+
229
+ l_h, l_r = pos_h[1] - pos_h[0], pos_r[1] - pos_r[0] # length (i.e. number of tokens) of head and relation
230
+
231
+ # iterate over all combinations of tokens in each triplet. This implementation is not very elegant, but it works.
232
+ for ih, ph in enumerate(range(pos_h[0], pos_h[1])): # iterate over all head tokens
233
+ for ir, pr in enumerate(range(pos_r[0], pos_r[1])): # iterate over all relation tokens
234
+ relative_position[ph, pr] = l_h - ih + ir
235
+ relative_position[pr, ph] = - (l_h - ih + ir)
236
+ use_additional_bucket[ph, pr] = False
237
+ use_additional_bucket[pr, ph] = False
238
+ for it, pt in enumerate(range(pos_t[0], pos_t[1])): # iterate over all tail tokens
239
+ relative_position[ph, pt] = l_h - ih + l_r + it
240
+ relative_position[pt, ph] = - (l_h - ih + l_r + it)
241
+ use_additional_bucket[ph, pt] = False
242
+ use_additional_bucket[pt, ph] = False
243
+ for ir, pr in enumerate(range(pos_r[0], pos_r[1])): # iterate over all relation tokens
244
+ for it, pt in enumerate(range(pos_t[0], pos_t[1])): # iterate over all tail tokens
245
+ relative_position[pr, pt] = l_r - ir + it
246
+ relative_position[pt, pr] = - (l_r - ir + it)
247
+ use_additional_bucket[pr, pt] = False
248
+ use_additional_bucket[pt, pr] = False
249
+
250
+ relation_counter[triplet[1]] += 1 # next time when that relation comes, then the next tokens will be used
251
+ if use_eos:
252
+ assert len(indices['</s>']) == 1, f"{indices['</s>'] = } should have length 1"
253
+ pos_eos = indices['</s>'][0] # position of head; tuple (start_index, end_index)
254
+ assert pos_eos[0] + 1 == pos_eos[1], pos_eos
255
+ pos_eos = pos_eos[0] # position of eos token
256
+
257
+ if eos == 'bidirectional':
258
+ relative_position[:, pos_eos] = +1e6
259
+ relative_position[pos_eos, :] = -1e6
260
+ relative_position[pos_eos, pos_eos] = 0
261
+ sparsity_mask[:, pos_eos] = True
262
+ sparsity_mask[pos_eos, :] = True
263
+ use_additional_bucket[:, pos_eos] = False
264
+ use_additional_bucket[pos_eos, :] = False
265
+ elif eos == 'unidirectional':
266
+ relative_position[:, pos_eos] = 1e6
267
+ relative_position[pos_eos, pos_eos] = 0
268
+ sparsity_mask[pos_eos, :] = False # no messages from eos to other tokens
269
+ sparsity_mask[:, pos_eos] = True
270
+ use_additional_bucket[:, pos_eos] = False
271
+ use_additional_bucket[pos_eos, :] = False
272
+ else:
273
+ raise ValueError(f'{eos = } is not a valid option.')
274
+
275
+ relative_position = relative_position.unsqueeze(0) # add batch dimension
276
+ sparsity_mask = sparsity_mask.unsqueeze(0) # add batch dimension
277
+ use_additional_bucket = use_additional_bucket.unsqueeze(0) # add batch dimension
278
+ return relative_position, sparsity_mask, use_additional_bucket
279
+
280
+ def graph_to_graphT5(g:Graph, tokenizer:T5Tokenizer, how:str, eos:str)->Data:
281
+ """
282
+ Convert a graph to a graphT5 input.
283
+ :param g: graph
284
+ :param tokenizer: tokenizer
285
+ :param how: how to represent the graph. Can be 'local' or 'global' for lGLM and gGLM respectively.
286
+ :param eos: end-of-sequence token. Can be `False` for not using an eos token. When using an eos token, there are two ways to use it: `bidirectional` means that the eos token is connected to every other node in the graph, with a relative position of positive infinity (from node to eos) or negative infinity (from eos to node). `unidirectional` means that the eos token is connected to every node in the graph with a relative position of positive infinity (from node to eos), but not the other way around (i.e. no connection from eos to other node). This means, that nodes do not get messages from the eos token, which perceives locality when using the local GLM
287
+ """
288
+ if not isinstance(g, Graph):
289
+ g = Graph(g)
290
+ eos = str(eos)
291
+ assert eos in ['False', 'bidirectional', 'unidirectional'], f"{eos = } must be either 'False', 'bidirectional', or 'unidirectional'"
292
+ use_eos:bool = eos != 'False'
293
+
294
+ str2tok = _get_str2tok(g, tokenizer) # get a dictionary mapping concepts and relations to their tokenized forms
295
+
296
+ sequence, indices, is_concept, concept_indices = _get_graphT5_input_sequence(g, str2tok, use_eos) # get input sequence (i.e. sequence that will be fed into the model for this graph
297
+ sequence_length = sequence.shape[1]
298
+
299
+ if how == 'local':
300
+ relative_position, sparsity_mask, use_additional_bucket = _get_graphT5_relativeposition_sparsitymask(g, indices, sequence_length, use_eos, eos)
301
+ num_additional_buckets = 0 # lGLM does not use additional buckets
302
+ elif how == 'global':
303
+ relative_position, sparsity_mask, use_additional_bucket = _get_global_graphT5_relativeposition_sparsitymask(g, indices, sequence_length, use_eos, eos)
304
+ num_additional_buckets = 1 # gGLM uses 1 additional bucket for long-ranged G2G connections
305
+ else:
306
+ raise ValueError(f"how must be either 'local' or 'global', but is {how}")
307
+
308
+ input_ids = sequence
309
+
310
+ data = Data(input_ids=input_ids, relative_position=relative_position, sparsity_mask=sparsity_mask, use_additional_bucket=use_additional_bucket, indices=indices, is_concept=is_concept, concept_indices=concept_indices, num_additional_buckets=num_additional_buckets)
311
+
312
+ return data
313
+
314
+ @cache
315
+ def _get_relative_position(size):
316
+ return torch.tensor([[i - j for i in range(size)] for j in range(size)], dtype=torch.long)
317
+
318
+ def get_embedding(
319
+ sequence_embedding: torch.Tensor,
320
+ indices: Dict[str, List[Tuple[int, int]]],
321
+ concept: str,
322
+ embedding_aggregation: str = "mean",
323
+ ):
324
+ """
325
+ Returns the embedding of a concept.
326
+ :param sequence_embedding: the embedding of the whole sequence. shape: (sequence_length, embedding_size)
327
+ :param indices: dictionary mapping each node to its start-index and end- in the sequence. Keys are nodes, values are lists of tuples (start_index, end_index). The lists have a length of 1 for concepts.
328
+ :param concept: the concept for which the embedding should be returned
329
+ :param embedding_aggregation: how the embedding of a concept should be aggregated. Either "mean" or "seq". "mean" returns the mean of all tokens of the concept. "seq" returns the embeddings of the all token of the concept.
330
+ :return: the aggregated embedding of the concept. shape (1, embedding_size) or (number_of_tokens, embedding_size).
331
+ """
332
+ assert concept in indices.keys(), f"{concept = } is not a node in the graph. {indices = }"
333
+ assert len(indices[concept]) == 1, f"{concept = } is not a concept, as concepts occur only once in the graph. {indices = }"
334
+
335
+ start, end = indices[concept][0]
336
+ sequence_embedding = sequence_embedding[start:end, :]
337
+ if embedding_aggregation == "mean":
338
+ return torch.mean(sequence_embedding, dim=0, keepdim=True)
339
+ elif embedding_aggregation == "seq":
340
+ return sequence_embedding
341
+ else:
342
+ raise NotImplementedError(f"{embedding_aggregation = } is not supported. Use either 'mean' or 'seq'.")
343
+
344
+ def add_text_to_graph_data(data, text, tokenizer, use_text):
345
+ if use_text in {'False', '', False, None}:
346
+ return None
347
+
348
+ text_seq = torch.tensor(tokenizer(text, padding=False)['input_ids']).unsqueeze(0)
349
+ new_input_ids = torch.cat([data.input_ids, text_seq], dim=1)
350
+
351
+ old_seq_len = data.input_ids.shape[1]
352
+ text_seq_len = text_seq.shape[1]
353
+ new_seq_len = new_input_ids.shape[1]
354
+
355
+ new_is_graph = torch.zeros(size=(1, new_seq_len), dtype=torch.bool)
356
+ new_is_graph[:, :old_seq_len] = True
357
+
358
+ if data.relative_position is None: # sequence transformer
359
+ assert data.sparsity_mask is None
360
+ assert data.use_additional_bucket is None
361
+ data.input_ids = new_input_ids
362
+ data.is_graph = new_is_graph
363
+ return None
364
+
365
+ new_relative_position = torch.zeros(size=(1, new_seq_len, new_seq_len), dtype=data.relative_position.dtype)
366
+ new_relative_position[:, :old_seq_len, :old_seq_len] = data.relative_position
367
+ new_relative_position[:, old_seq_len:, old_seq_len:] = _get_relative_position(text_seq_len)
368
+
369
+ new_sparsity_mask = torch.zeros(size=(1, new_seq_len, new_seq_len), dtype=data.sparsity_mask.dtype)
370
+ new_sparsity_mask[:, :old_seq_len, :old_seq_len] = data.sparsity_mask
371
+ new_sparsity_mask[:, old_seq_len:, old_seq_len:] = True
372
+
373
+ new_use_additional_bucket = torch.zeros(size=(1, new_seq_len, new_seq_len), dtype=data.use_additional_bucket.dtype)
374
+ new_use_additional_bucket[:, :old_seq_len, :old_seq_len] = data.use_additional_bucket
375
+ new_use_additional_bucket[:, old_seq_len:, old_seq_len:] = False # could change that if we want T2T and local G2G relations to be learned separately
376
+
377
+ if use_text in {'FullyConnected', True}:
378
+ new_sparsity_mask[:, old_seq_len:, :old_seq_len] = True
379
+ new_sparsity_mask[:, :old_seq_len, old_seq_len:] = True
380
+
381
+ new_use_additional_bucket[:, old_seq_len:, :old_seq_len] = True
382
+ new_use_additional_bucket[:, :old_seq_len, old_seq_len:] = True
383
+
384
+ new_relative_position[:, old_seq_len:, :old_seq_len] = data.num_additional_buckets
385
+ new_relative_position[:, :old_seq_len, old_seq_len:] = data.num_additional_buckets + 1
386
+
387
+ new_num_additional_buckets = data.num_additional_buckets + 2
388
+ else:
389
+ raise ValueError(f"unknown use_text {use_text} (type {type(use_text)})")
390
+
391
+ data.input_ids = new_input_ids
392
+ data.relative_position = new_relative_position
393
+ data.sparsity_mask = new_sparsity_mask
394
+ data.use_additional_bucket = new_use_additional_bucket
395
+ data.num_additional_buckets = new_num_additional_buckets
396
+ data.is_graph = new_is_graph
397
+ return None
398
+
399
+ class DataProcessor():
400
+ @staticmethod
401
+ def encode_graph(tokenizer, g:Union[Graph,list[tuple[str,str,str]]], text:Optional[str]=None, how:Literal['global', 'local']='global', eos:str="False")->Data:
402
+ """
403
+ convert graph to suitable input for the model.
404
+ :param tokenizer: tokenizer
405
+ :param g: graph
406
+ :param text: text to add to the graph. Can be None if no text should be added.
407
+ :param how: how to represent the graph. Can be 'local' or 'global' for lGLM and gGLM respectively.
408
+ :param eos: end-of-sequence token. Can be `False` for not using an eos token. This is the method used in the paper. When using an eos token, there are two ways to use it: `bidirectional` means that the eos token is connected to every other node in the graph. `unidirectional` means that the eos token is connected to every node in the graph (from node to eos), but not the other way around (i.e. no connection from eos to other node). This means, that nodes do not get messages from the eos token, which perceives locality when using the local GLM
409
+ :return: Data object
410
+ """
411
+ if not isinstance(g, Graph):
412
+ g = Graph(g)
413
+ data = graph_to_graphT5(g, tokenizer, how, eos)
414
+ if text is not None:
415
+ add_text_to_graph_data(data, text, tokenizer, use_text=True)
416
+ return data
417
+
418
+ @staticmethod
419
+ def to_batch(data_instances:list[Data], tokenizer, max_seq_len:Optional[int]=None, device:str='cpu', **kwargs)->dict:
420
+ """
421
+ converts list of data instances to batched inputs for GLM forward call.
422
+ :param datas: list of Data instances
423
+ :param max_seq_len: maximum sequence length
424
+ :param tokenizer: tokenizer
425
+ :param device: device
426
+ :return: dictionary with keys 'input_ids', 'relative_position', 'sparsity_mask', and 'use_additional_bucket'
427
+ """
428
+ current_max_seq_len = max([data.input_ids.shape[1] for data in data_instances])
429
+ if max_seq_len is None:
430
+ max_seq_len = current_max_seq_len
431
+ else:
432
+ max_seq_len = min(max_seq_len, current_max_seq_len)
433
+
434
+ if data_instances[0].relative_position is None:
435
+ assert data_instances[0].sparsity_mask is None
436
+ assert data_instances[0].use_additional_bucket is None
437
+ is_sequence_transformer = True
438
+ else:
439
+ assert data_instances[0].sparsity_mask is not None
440
+ assert data_instances[0].use_additional_bucket is not None
441
+ is_sequence_transformer = False
442
+
443
+ # intialize tensors
444
+ input_ids = torch.ones((len(data_instances), max_seq_len), dtype=torch.long, device=device) * tokenizer.pad_token_id
445
+ if is_sequence_transformer:
446
+ relative_position = None
447
+ sparsity_mask = None
448
+ use_additional_bucket = None
449
+ else:
450
+ relative_position = torch.zeros((len(data_instances), max_seq_len, max_seq_len), dtype=torch.long, device=device)
451
+ sparsity_mask = torch.zeros((len(data_instances), max_seq_len, max_seq_len), dtype=torch.bool, device=device)
452
+ use_additional_bucket = torch.zeros((len(data_instances), max_seq_len, max_seq_len), dtype=torch.bool, device=device)
453
+
454
+ # fill tensors
455
+ for i, data in enumerate(data_instances):
456
+ instance_len = min(data.input_ids.shape[1], max_seq_len)
457
+ input_ids[i, :instance_len] = data.input_ids[:, :instance_len]
458
+ if not is_sequence_transformer:
459
+ relative_position[i, :instance_len, :instance_len] = data.relative_position[:, :instance_len, :instance_len]
460
+ sparsity_mask[i, :instance_len, :instance_len] = data.sparsity_mask[:, :instance_len, :instance_len]
461
+ use_additional_bucket[i, :instance_len, :instance_len] = data.use_additional_bucket[:, :instance_len, :instance_len]
462
+
463
+ model_input = {
464
+ 'input_ids': input_ids,
465
+ 'relative_position': relative_position,
466
+ 'sparsity_mask': sparsity_mask,
467
+ 'use_additional_bucket': use_additional_bucket,
468
+ **kwargs
469
+ }
470
+ return model_input
471
+
472
+ @staticmethod
473
+ def get_embedding(sequence_embedding:torch.Tensor, indices:Dict[str,List[Tuple[int, int]]], concept:str, embedding_aggregation:str="mean"):
474
+ """
475
+ Returns embedding of a concept.
476
+ :param sequence_embedding: the embedding of the whole sequence. shape: (sequence_length, embedding_size)
477
+ :param indices: dictionary mapping each node to its start- and end-index in the sequence. Keys are nodes, values are lists of tuples (start_index, end_index). The lists have a length of 1 for concepts. indices is part of the Data object.
478
+ :param concept: the concept for which the embedding should be returned.
479
+ :param embedding_aggregation: how the embedding of a concept should be aggregated. Either "mean" or "seq". "mean" returns the mean of all tokens of the concept. "seq" returns the embeddings of the all token of the concept.
480
+ :return: the aggregated embedding of the concept. shape (1, embedding_size) or (number_of_tokens, embedding_size).
481
+ """
482
+ return get_embedding(sequence_embedding, indices, concept, embedding_aggregation)
483
+