Zhibin Lu
commited on
Commit
•
3cbf7e6
1
Parent(s):
cbf28bd
init stracture, add safe model
Browse files- LICENSE.txt +201 -0
- README.md +37 -5
- __init__.py +76 -0
- pytorch_model.bin → model.safetensors +2 -2
- modeling_graph.py +433 -0
LICENSE.txt
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
README.md
CHANGED
@@ -12,7 +12,17 @@ datasets:
|
|
12 |
|
13 |
This model is a VGCN-BERT model based on [DistilBert-base-uncased](https://huggingface.co/distilbert-base-uncased) version. The original paper is [VGCN-BERT](https://arxiv.org/abs/2004.05707).
|
14 |
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
- First prepare WGraph symmetric adjacency matrix
|
18 |
|
@@ -20,9 +30,9 @@ This model is a VGCN-BERT model based on [DistilBert-base-uncased](https://huggi
|
|
20 |
import transformers as tfr
|
21 |
from transformers.models.vgcn_bert.modeling_graph import WordGraph
|
22 |
|
23 |
-
tokenizer
|
24 |
-
|
25 |
-
|
26 |
# 1st method: Build graph using NPMI statistical method from training corpus
|
27 |
wgraph = WordGraph(rows=train_valid_df["text"], tokenizer=tokenizer)
|
28 |
# 2nd method: Build graph from pre-defined entity relationship tuple with weight
|
@@ -51,5 +61,27 @@ output = model(**encoded_input)
|
|
51 |
|
52 |
|
53 |
## Fine-tune model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
|
|
|
|
|
|
12 |
|
13 |
This model is a VGCN-BERT model based on [DistilBert-base-uncased](https://huggingface.co/distilbert-base-uncased) version. The original paper is [VGCN-BERT](https://arxiv.org/abs/2004.05707).
|
14 |
|
15 |
+
> Much progress has been made recently on text classification with methods based on neural networks. In particular, models using attention mechanism such as BERT have shown to have the capability of capturing the contextual information within a sentence or document. However, their ability of capturing the global information about the vocabulary of a language is more limited. This latter is the strength of Graph Convolutional Networks (GCN). In this paper, we propose VGCN-BERT model which combines the capability of BERT with a Vocabulary Graph Convolutional Network (VGCN). Local information and global information interact through different layers of BERT, allowing them to influence mutually and to build together a final representation for classification. In our experiments on several text classification datasets, our approach outperforms BERT and GCN alone, and achieve higher effectiveness than that reported in previous studies.
|
16 |
+
|
17 |
+
The original implementation is in my gitlab [vgcn-bert repo](https://github.com/Louis-udm/VGCN-BERT), but recently I updated the algorithm and implemented this new version for integrating in Transformer, the new version has the following improvements:
|
18 |
+
- Greatly speeds up the calculation speed of embedding vocabulary graph convolutinal network (or Word Graph embedding). Taking CoLa as an example, the new model only increases the training time by 11% compared with the base model
|
19 |
+
- Updated subgraph selection algorithm.
|
20 |
+
- Currently using DistilBert as the base model, but it is easy to migrate to other models.
|
21 |
+
- Provide two graph construction methods in vgcn_bert/modeling_graph.py (the same NPMI statistical method as the paper, and the predefined entity-relationship mapping method)
|
22 |
+
|
23 |
+
I hope that after integrating into transformers, someone can discover some more practical use case and share to me. I am ashamed to say that I have not discovered too much real use cases myself, mainly because the word-grounded graph obtained through statistical methods has limited improvement on the LLM model. I think its potential application should be when there are specific/customized graphs that need to be integrated into LLM.
|
24 |
+
|
25 |
+
## How to use
|
26 |
|
27 |
- First prepare WGraph symmetric adjacency matrix
|
28 |
|
|
|
30 |
import transformers as tfr
|
31 |
from transformers.models.vgcn_bert.modeling_graph import WordGraph
|
32 |
|
33 |
+
# Use DistilBert tokenizer, that is corresponding to the base model of this version
|
34 |
+
tokenizer = tfr.AutoTokenizer.from_pretrained("distilbert-base-uncased")
|
35 |
+
|
36 |
# 1st method: Build graph using NPMI statistical method from training corpus
|
37 |
wgraph = WordGraph(rows=train_valid_df["text"], tokenizer=tokenizer)
|
38 |
# 2nd method: Build graph from pre-defined entity relationship tuple with weight
|
|
|
61 |
|
62 |
|
63 |
## Fine-tune model
|
64 |
+
It's better fin-tune vgcn-bert model for the specific tasks.
|
65 |
+
|
66 |
+
## Citation
|
67 |
+
If you make use of this code or the VGCN-BERT approach in your work, please cite the following paper:
|
68 |
+
|
69 |
+
@inproceedings{ZhibinluGraphEmbedding,
|
70 |
+
author = {Zhibin Lu and Pan Du and Jian-Yun Nie},
|
71 |
+
title = {VGCN-BERT: Augmenting BERT with Graph Embedding for Text Classification},
|
72 |
+
booktitle = {Advances in Information Retrieval - 42nd European Conference on {IR}
|
73 |
+
Research, {ECIR} 2020, Lisbon, Portugal, April 14-17, 2020, Proceedings,
|
74 |
+
Part {I}},
|
75 |
+
series = {Lecture Notes in Computer Science},
|
76 |
+
volume = {12035},
|
77 |
+
pages = {369--382},
|
78 |
+
publisher = {Springer},
|
79 |
+
year = {2020},
|
80 |
+
}
|
81 |
+
|
82 |
+
## License
|
83 |
+
VGCN-BERT is made available under the Apache 2.0 license.
|
84 |
|
85 |
+
## Contact
|
86 |
+
[Zhibin.Lu](mailto: Zhibin.Lu.ai@gmail.com)
|
87 |
+
[louis-udm in GitHub](https://github.com/Louis-udm)
|
__init__.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
from typing import TYPE_CHECKING
|
16 |
+
|
17 |
+
from transformers.utils import (
|
18 |
+
OptionalDependencyNotAvailable,
|
19 |
+
_LazyModule,
|
20 |
+
is_torch_available,
|
21 |
+
)
|
22 |
+
|
23 |
+
|
24 |
+
_import_structure = {
|
25 |
+
"configuration_vgcn_bert": [
|
26 |
+
"VGCNBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
27 |
+
"VGCNBertConfig",
|
28 |
+
"VGCNBertOnnxConfig",
|
29 |
+
],
|
30 |
+
}
|
31 |
+
|
32 |
+
try:
|
33 |
+
if not is_torch_available():
|
34 |
+
raise OptionalDependencyNotAvailable()
|
35 |
+
except OptionalDependencyNotAvailable:
|
36 |
+
pass
|
37 |
+
else:
|
38 |
+
_import_structure["modeling_vgcn_bert"] = [
|
39 |
+
"VGCNBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
|
40 |
+
"VGCNBertForMaskedLM",
|
41 |
+
"VGCNBertForMultipleChoice",
|
42 |
+
"VGCNBertForQuestionAnswering",
|
43 |
+
"VGCNBertForSequenceClassification",
|
44 |
+
"VGCNBertForTokenClassification",
|
45 |
+
"VGCNBertModel",
|
46 |
+
"VGCNBertPreTrainedModel",
|
47 |
+
]
|
48 |
+
|
49 |
+
if TYPE_CHECKING:
|
50 |
+
from .configuration_vgcn_bert import (
|
51 |
+
VGCNBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
52 |
+
VGCNBertConfig,
|
53 |
+
VGCNBertOnnxConfig,
|
54 |
+
)
|
55 |
+
|
56 |
+
try:
|
57 |
+
if not is_torch_available():
|
58 |
+
raise OptionalDependencyNotAvailable()
|
59 |
+
except OptionalDependencyNotAvailable:
|
60 |
+
pass
|
61 |
+
else:
|
62 |
+
from .modeling_vgcn_bert import (
|
63 |
+
VGCNBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
|
64 |
+
VGCNBertForMaskedLM,
|
65 |
+
VGCNBertForMultipleChoice,
|
66 |
+
VGCNBertForQuestionAnswering,
|
67 |
+
VGCNBertForSequenceClassification,
|
68 |
+
VGCNBertForTokenClassification,
|
69 |
+
VGCNBertModel,
|
70 |
+
VGCNBertPreTrainedModel,
|
71 |
+
)
|
72 |
+
|
73 |
+
else:
|
74 |
+
import sys
|
75 |
+
|
76 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
pytorch_model.bin → model.safetensors
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a2dbd66732eaaee98a88a2bb51d782214ce2885dd835a939f8ad129ace78a39c
|
3 |
+
size 267954672
|
modeling_graph.py
ADDED
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, 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 |
+
|
16 |
+
"""Construct the Word/Entity Graph from text samples or pre-defined word-pairs relations
|
17 |
+
|
18 |
+
Approaches: NPMI, PMI, pre-defined word-pairs relations.
|
19 |
+
|
20 |
+
You may (or not) first preprocess the text before build the graph,
|
21 |
+
e.g. Stopword removal, String cleaning, Stemming, Nomolization, Lemmatization
|
22 |
+
|
23 |
+
"""
|
24 |
+
|
25 |
+
from collections import Counter
|
26 |
+
from math import log
|
27 |
+
from typing import Dict, List, Tuple
|
28 |
+
import torch
|
29 |
+
|
30 |
+
import numpy as np
|
31 |
+
import scipy.sparse as sp
|
32 |
+
from transformers.tokenization_utils import PreTrainedTokenizerBase
|
33 |
+
from transformers.configuration_utils import PretrainedConfig
|
34 |
+
|
35 |
+
ENGLISH_STOP_WORDS = frozenset(
|
36 |
+
{
|
37 |
+
"herself",
|
38 |
+
"each",
|
39 |
+
"him",
|
40 |
+
"been",
|
41 |
+
"only",
|
42 |
+
"yourselves",
|
43 |
+
"into",
|
44 |
+
"where",
|
45 |
+
"them",
|
46 |
+
"very",
|
47 |
+
"we",
|
48 |
+
"that",
|
49 |
+
"re",
|
50 |
+
"too",
|
51 |
+
"some",
|
52 |
+
"what",
|
53 |
+
"those",
|
54 |
+
"me",
|
55 |
+
"whom",
|
56 |
+
"have",
|
57 |
+
"yours",
|
58 |
+
"an",
|
59 |
+
"during",
|
60 |
+
"any",
|
61 |
+
"nor",
|
62 |
+
"ourselves",
|
63 |
+
"has",
|
64 |
+
"do",
|
65 |
+
"when",
|
66 |
+
"about",
|
67 |
+
"same",
|
68 |
+
"our",
|
69 |
+
"then",
|
70 |
+
"himself",
|
71 |
+
"their",
|
72 |
+
"all",
|
73 |
+
"no",
|
74 |
+
"a",
|
75 |
+
"hers",
|
76 |
+
"off",
|
77 |
+
"why",
|
78 |
+
"how",
|
79 |
+
"more",
|
80 |
+
"between",
|
81 |
+
"until",
|
82 |
+
"not",
|
83 |
+
"over",
|
84 |
+
"your",
|
85 |
+
"by",
|
86 |
+
"here",
|
87 |
+
"most",
|
88 |
+
"above",
|
89 |
+
"up",
|
90 |
+
"of",
|
91 |
+
"is",
|
92 |
+
"after",
|
93 |
+
"from",
|
94 |
+
"being",
|
95 |
+
"i",
|
96 |
+
"as",
|
97 |
+
"other",
|
98 |
+
"so",
|
99 |
+
"her",
|
100 |
+
"ours",
|
101 |
+
"on",
|
102 |
+
"because",
|
103 |
+
"against",
|
104 |
+
"and",
|
105 |
+
"out",
|
106 |
+
"had",
|
107 |
+
"these",
|
108 |
+
"at",
|
109 |
+
"both",
|
110 |
+
"down",
|
111 |
+
"you",
|
112 |
+
"can",
|
113 |
+
"she",
|
114 |
+
"few",
|
115 |
+
"the",
|
116 |
+
"if",
|
117 |
+
"it",
|
118 |
+
"to",
|
119 |
+
"but",
|
120 |
+
"its",
|
121 |
+
"be",
|
122 |
+
"he",
|
123 |
+
"once",
|
124 |
+
"further",
|
125 |
+
"such",
|
126 |
+
"there",
|
127 |
+
"through",
|
128 |
+
"are",
|
129 |
+
"themselves",
|
130 |
+
"which",
|
131 |
+
"in",
|
132 |
+
"now",
|
133 |
+
"his",
|
134 |
+
"yourself",
|
135 |
+
"this",
|
136 |
+
"were",
|
137 |
+
"below",
|
138 |
+
"should",
|
139 |
+
"my",
|
140 |
+
"myself",
|
141 |
+
"am",
|
142 |
+
"or",
|
143 |
+
"while",
|
144 |
+
"itself",
|
145 |
+
"again",
|
146 |
+
"with",
|
147 |
+
"they",
|
148 |
+
"will",
|
149 |
+
"own",
|
150 |
+
"than",
|
151 |
+
"before",
|
152 |
+
"under",
|
153 |
+
"was",
|
154 |
+
"for",
|
155 |
+
"who",
|
156 |
+
}
|
157 |
+
)
|
158 |
+
|
159 |
+
|
160 |
+
class WordGraph:
|
161 |
+
"""
|
162 |
+
Word graph based on adjacency matrix, construct from text samples or pre-defined word-pair relations
|
163 |
+
|
164 |
+
Params:
|
165 |
+
`rows`: List[str] of text samples, or pre-defined word-pair relations: List[Tuple[str, str, float]]
|
166 |
+
`tokenizer`: The same pretrained tokenizer that is used for the model late.
|
167 |
+
`window_size`: Available only for statistics generation (rows is text samples).
|
168 |
+
Size of the sliding window for collecting the pieces of text
|
169 |
+
and further calculate the NPMI value, default is 20.
|
170 |
+
`algorithm`: Available only for statistics generation (rows is text samples) -- "npmi" or "pmi", default is "npmi".
|
171 |
+
`edge_threshold`: Available only for statistics generation (rows is text samples). Graph edge value threshold, default is 0. Edge value is between -1 to 1.
|
172 |
+
`remove_stopwords`: Build word graph with the words that are not stopwords, default is False.
|
173 |
+
`min_freq_to_keep`: Available only for statistics generation (rows is text samples). Build word graph with the words that occurred at least n times in the corpus, default is 2.
|
174 |
+
|
175 |
+
Properties:
|
176 |
+
`adjacency_matrix`: scipy.sparse.csr_matrix, the word graph in sparse adjacency matrix form.
|
177 |
+
`vocab_indices`: indices of word graph vocabulary words.
|
178 |
+
`wgraph_id_to_tokenizer_id_map`: map from word graph vocabulary word id to tokenizer vocabulary word id.
|
179 |
+
|
180 |
+
"""
|
181 |
+
|
182 |
+
def __init__(
|
183 |
+
self,
|
184 |
+
rows: list,
|
185 |
+
tokenizer: PreTrainedTokenizerBase,
|
186 |
+
window_size=20,
|
187 |
+
algorithm="npmi",
|
188 |
+
edge_threshold=0.0,
|
189 |
+
remove_stopwords=False,
|
190 |
+
min_freq_to_keep=2,
|
191 |
+
):
|
192 |
+
if type(rows[0]) == tuple:
|
193 |
+
(
|
194 |
+
self.adjacency_matrix,
|
195 |
+
self.vocab_indices,
|
196 |
+
self.wgraph_id_to_tokenizer_id_map,
|
197 |
+
) = _build_predefined_graph(rows, tokenizer, remove_stopwords)
|
198 |
+
else:
|
199 |
+
(
|
200 |
+
self.adjacency_matrix,
|
201 |
+
self.vocab_indices,
|
202 |
+
self.wgraph_id_to_tokenizer_id_map,
|
203 |
+
) = _build_pmi_graph(
|
204 |
+
rows, tokenizer, window_size, algorithm, edge_threshold, remove_stopwords, min_freq_to_keep
|
205 |
+
)
|
206 |
+
|
207 |
+
def normalized(self):
|
208 |
+
return _normalize_adj(self.adjacency_matrix) if self.adjacency_matrix is not None else None
|
209 |
+
|
210 |
+
def to_torch_sparse(self):
|
211 |
+
if self.adjacency_matrix is None:
|
212 |
+
return None
|
213 |
+
adj = _normalize_adj(self.adjacency_matrix)
|
214 |
+
return _scipy_to_torch(adj)
|
215 |
+
|
216 |
+
|
217 |
+
def _normalize_adj(adj):
|
218 |
+
"""Symmetrically normalize adjacency matrix."""
|
219 |
+
rowsum = np.array(adj.sum(1)) # D-degree matrix
|
220 |
+
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
|
221 |
+
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.0
|
222 |
+
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
|
223 |
+
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)
|
224 |
+
|
225 |
+
|
226 |
+
def _scipy_to_torch(sparse):
|
227 |
+
sparse = sparse.tocoo() if sparse.getformat() != "coo" else sparse
|
228 |
+
i = torch.LongTensor(np.vstack((sparse.row, sparse.col)))
|
229 |
+
v = torch.from_numpy(sparse.data)
|
230 |
+
return torch.sparse_coo_tensor(i, v, torch.Size(sparse.shape)).coalesce()
|
231 |
+
|
232 |
+
|
233 |
+
def _delete_special_terms(words: list, terms: set):
|
234 |
+
return set([w for w in words if w not in terms])
|
235 |
+
|
236 |
+
|
237 |
+
def _build_pmi_graph(
|
238 |
+
texts: List[str],
|
239 |
+
tokenizer: PreTrainedTokenizerBase,
|
240 |
+
window_size=20,
|
241 |
+
algorithm="npmi",
|
242 |
+
edge_threshold=0.0,
|
243 |
+
remove_stopwords=False,
|
244 |
+
min_freq_to_keep=2,
|
245 |
+
) -> Tuple[sp.csr_matrix, Dict[str, int], Dict[int, int]]:
|
246 |
+
"""
|
247 |
+
Build statistical word graph from text samples using PMI or NPMI algorithm.
|
248 |
+
"""
|
249 |
+
|
250 |
+
# Tokenize the text samples. The tokenizer should be same as that in the combined Bert-like model.
|
251 |
+
# Remove stopwords and special terms
|
252 |
+
# Get vocabulary and the word frequency
|
253 |
+
words_to_remove = (
|
254 |
+
set({"[CLS]", "[SEP]"}).union(ENGLISH_STOP_WORDS) if remove_stopwords else set({"[CLS]", "[SEP]"})
|
255 |
+
)
|
256 |
+
vocab_counter = Counter()
|
257 |
+
texts_words = []
|
258 |
+
for t in texts:
|
259 |
+
words = tokenizer.tokenize(t)
|
260 |
+
words = _delete_special_terms(words, words_to_remove)
|
261 |
+
if len(words) > 0:
|
262 |
+
vocab_counter.update(Counter(words))
|
263 |
+
texts_words.append(words)
|
264 |
+
|
265 |
+
# Set [PAD] as the head of vocabulary
|
266 |
+
# Remove word with freq<n and re generate texts
|
267 |
+
new_vocab_counter = Counter({"[PAD]": 0})
|
268 |
+
new_vocab_counter.update(
|
269 |
+
Counter({k: v for k, v in vocab_counter.items() if v >= min_freq_to_keep})
|
270 |
+
if min_freq_to_keep > 1
|
271 |
+
else vocab_counter
|
272 |
+
)
|
273 |
+
vocab_counter = new_vocab_counter
|
274 |
+
|
275 |
+
# Generate new texts by removing words with freq<n
|
276 |
+
if min_freq_to_keep > 1:
|
277 |
+
texts_words = [list(filter(lambda w: vocab_counter[w] >= min_freq_to_keep, words)) for words in texts_words]
|
278 |
+
texts = [" ".join(words).strip() for words in texts_words if len(words) > 0]
|
279 |
+
|
280 |
+
vocab_size = len(vocab_counter)
|
281 |
+
vocab = list(vocab_counter.keys())
|
282 |
+
assert vocab[0] == "[PAD]"
|
283 |
+
vocab_indices = {k: i for i, k in enumerate(vocab)}
|
284 |
+
|
285 |
+
# Get the pieces from sliding windows
|
286 |
+
windows = []
|
287 |
+
for t in texts:
|
288 |
+
words = t.split()
|
289 |
+
word_ids = [vocab_indices[w] for w in words]
|
290 |
+
length = len(word_ids)
|
291 |
+
if length <= window_size:
|
292 |
+
windows.append(word_ids)
|
293 |
+
else:
|
294 |
+
for j in range(length - window_size + 1):
|
295 |
+
word_ids = word_ids[j : j + window_size]
|
296 |
+
windows.append(word_ids)
|
297 |
+
|
298 |
+
# Get the window-count that every word appeared (count 1 for the same window).
|
299 |
+
# Get window-count that every word-pair appeared (count 1 for the same window).
|
300 |
+
vocab_window_counter = Counter()
|
301 |
+
word_pair_window_counter = Counter()
|
302 |
+
for word_ids in windows:
|
303 |
+
word_ids = list(set(word_ids))
|
304 |
+
vocab_window_counter.update(Counter(word_ids))
|
305 |
+
word_pair_window_counter.update(
|
306 |
+
Counter(
|
307 |
+
[
|
308 |
+
f(i, j)
|
309 |
+
# (word_ids[i], word_ids[j])
|
310 |
+
for i in range(1, len(word_ids))
|
311 |
+
for j in range(i)
|
312 |
+
# adding inverse pair
|
313 |
+
for f in (lambda x, y: (word_ids[x], word_ids[y]), lambda x, y: (word_ids[y], word_ids[x]))
|
314 |
+
]
|
315 |
+
)
|
316 |
+
)
|
317 |
+
|
318 |
+
# Calculate NPMI
|
319 |
+
vocab_adj_row = []
|
320 |
+
vocab_adj_col = []
|
321 |
+
vocab_adj_weight = []
|
322 |
+
|
323 |
+
total_windows = len(windows)
|
324 |
+
for wid_pair in word_pair_window_counter.keys():
|
325 |
+
i, j = wid_pair
|
326 |
+
pair_count = word_pair_window_counter[wid_pair]
|
327 |
+
i_count = vocab_window_counter[i]
|
328 |
+
j_count = vocab_window_counter[j]
|
329 |
+
value = (
|
330 |
+
(log(1.0 * i_count * j_count / (total_windows**2)) / log(1.0 * pair_count / total_windows) - 1)
|
331 |
+
if algorithm == "npmi"
|
332 |
+
else (log((1.0 * pair_count / total_windows) / (1.0 * i_count * j_count / (total_windows**2))))
|
333 |
+
)
|
334 |
+
if value > edge_threshold:
|
335 |
+
vocab_adj_row.append(i)
|
336 |
+
vocab_adj_col.append(j)
|
337 |
+
vocab_adj_weight.append(value)
|
338 |
+
|
339 |
+
# Build vocabulary adjacency matrix
|
340 |
+
vocab_adj = sp.csr_matrix(
|
341 |
+
(vocab_adj_weight, (vocab_adj_row, vocab_adj_col)),
|
342 |
+
shape=(vocab_size, vocab_size),
|
343 |
+
dtype=np.float32,
|
344 |
+
)
|
345 |
+
vocab_adj.setdiag(1.0)
|
346 |
+
|
347 |
+
# Padding the first row and column, "[PAD]" is the first word in the vocabulary.
|
348 |
+
assert vocab_adj[0, :].sum() == 1
|
349 |
+
assert vocab_adj[:, 0].sum() == 1
|
350 |
+
vocab_adj[:, 0] = 0
|
351 |
+
vocab_adj[0, :] = 0
|
352 |
+
|
353 |
+
wgraph_id_to_tokenizer_id_map = {v: tokenizer.vocab[k] for k, v in vocab_indices.items()}
|
354 |
+
wgraph_id_to_tokenizer_id_map = dict(sorted(wgraph_id_to_tokenizer_id_map.items()))
|
355 |
+
|
356 |
+
return (
|
357 |
+
vocab_adj,
|
358 |
+
vocab_indices,
|
359 |
+
wgraph_id_to_tokenizer_id_map,
|
360 |
+
)
|
361 |
+
|
362 |
+
|
363 |
+
def _build_predefined_graph(
|
364 |
+
words_relations: List[Tuple[str, str, float]], tokenizer: PreTrainedTokenizerBase, remove_stopwords: bool = False
|
365 |
+
) -> Tuple[sp.csr_matrix, Dict[str, int], Dict[int, int]]:
|
366 |
+
"""
|
367 |
+
Build pre-defined wgraph from a list of word pairs and their pre-defined relations (edge value).
|
368 |
+
"""
|
369 |
+
|
370 |
+
# Tokenize the text samples. The tokenizer should be same as that in the combined Bert-like model.
|
371 |
+
# Remove stopwords and special terms
|
372 |
+
# Get vocabulary and the word frequency
|
373 |
+
words_to_remove = (
|
374 |
+
set({"[CLS]", "[SEP]"}).union(ENGLISH_STOP_WORDS) if remove_stopwords else set({"[CLS]", "[SEP]"})
|
375 |
+
)
|
376 |
+
vocab_counter = Counter({"[PAD]": 0})
|
377 |
+
word_pairs = {}
|
378 |
+
for w1, w2, v in words_relations:
|
379 |
+
w1_subwords = tokenizer.tokenize(w1)
|
380 |
+
w1_subwords = _delete_special_terms(w1_subwords, words_to_remove)
|
381 |
+
w2_subwords = tokenizer.tokenize(w2)
|
382 |
+
w2_subwords = _delete_special_terms(w2_subwords, words_to_remove)
|
383 |
+
vocab_counter.update(Counter(w1_subwords))
|
384 |
+
vocab_counter.update(Counter(w2_subwords))
|
385 |
+
for sw1 in w1_subwords:
|
386 |
+
for sw2 in w2_subwords:
|
387 |
+
if sw1 != sw2:
|
388 |
+
word_pairs.setdefault((sw1, sw2), v)
|
389 |
+
|
390 |
+
vocab_size = len(vocab_counter)
|
391 |
+
vocab = list(vocab_counter.keys())
|
392 |
+
assert vocab[0] == "[PAD]"
|
393 |
+
vocab_indices = {k: i for i, k in enumerate(vocab)}
|
394 |
+
|
395 |
+
# bulid adjacency matrix
|
396 |
+
vocab_adj_row = []
|
397 |
+
vocab_adj_col = []
|
398 |
+
vocab_adj_weight = []
|
399 |
+
for (w1, w2), v in word_pairs.items():
|
400 |
+
vocab_adj_row.append(vocab_indices[w1])
|
401 |
+
vocab_adj_col.append(vocab_indices[w2])
|
402 |
+
vocab_adj_weight.append(v)
|
403 |
+
# adding inverse
|
404 |
+
vocab_adj_row.append(vocab_indices[w2])
|
405 |
+
vocab_adj_col.append(vocab_indices[w1])
|
406 |
+
vocab_adj_weight.append(v)
|
407 |
+
|
408 |
+
# Build vocabulary adjacency matrix
|
409 |
+
vocab_adj = sp.csr_matrix(
|
410 |
+
(vocab_adj_weight, (vocab_adj_row, vocab_adj_col)),
|
411 |
+
shape=(vocab_size, vocab_size),
|
412 |
+
dtype=np.float32,
|
413 |
+
)
|
414 |
+
vocab_adj.setdiag(1.0)
|
415 |
+
|
416 |
+
# Padding the first row and column, "[PAD]" is the first word in the vocabulary.
|
417 |
+
assert vocab_adj[0, :].sum() == 1
|
418 |
+
assert vocab_adj[:, 0].sum() == 1
|
419 |
+
vocab_adj[:, 0] = 0
|
420 |
+
vocab_adj[0, :] = 0
|
421 |
+
|
422 |
+
wgraph_id_to_tokenizer_id_map = {v: tokenizer.vocab[k] for k, v in vocab_indices.items()}
|
423 |
+
wgraph_id_to_tokenizer_id_map = dict(sorted(wgraph_id_to_tokenizer_id_map.items()))
|
424 |
+
|
425 |
+
return (
|
426 |
+
vocab_adj,
|
427 |
+
vocab_indices,
|
428 |
+
wgraph_id_to_tokenizer_id_map,
|
429 |
+
)
|
430 |
+
|
431 |
+
|
432 |
+
# TODO: build knowledge graph from a list of RDF triples
|
433 |
+
# def _build_knowledge_graph
|