KoichiYasuoka commited on
Commit
b352112
1 Parent(s): d7f4c35

initial release

Browse files
Files changed (9) hide show
  1. README.md +30 -0
  2. config.json +374 -0
  3. maker.py +109 -0
  4. pytorch_model.bin +3 -0
  5. special_tokens_map.json +44 -0
  6. tokenizer.json +0 -0
  7. tokenizer.model +3 -0
  8. tokenizer_config.json +44 -0
  9. ud.py +142 -0
README.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - "ja"
4
+ tags:
5
+ - "japanese"
6
+ - "pos"
7
+ - "dependency-parsing"
8
+ base_model: KoichiYasuoka/karasu-1.1B-upos
9
+ datasets:
10
+ - "universal_dependencies"
11
+ license: "apache-2.0"
12
+ pipeline_tag: "token-classification"
13
+ widget:
14
+ - text: "全学年にわたって小学校の国語の教科書に挿し絵が用いられている"
15
+ ---
16
+
17
+ # karasu-1.1B-ud-causal
18
+
19
+ ## Model Description
20
+
21
+ This is a GPT-2 model pretrained for POS-tagging and dependency-parsing, derived from [karasu-1.1B-upos](https://huggingface.co/KoichiYasuoka/karasu-1.1B-upos) and [UD_Japanese-GSDLUW](https://github.com/UniversalDependencies/UD_Japanese-GSDLUW).
22
+
23
+ ## How to Use
24
+
25
+ ```
26
+ from transformers import pipeline
27
+ nlp=pipeline("universal-dependencies","KoichiYasuoka/karasu-1.1B-ud-causal",trust_remote_code=True)
28
+ print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
29
+ ```
30
+
config.json ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForTokenClassification"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 1,
8
+ "custom_pipelines": {
9
+ "upos": {
10
+ "impl": "ud.BellmanFordTokenClassificationPipeline",
11
+ "pt": "AutoModelForTokenClassification"
12
+ },
13
+ "universal-dependencies": {
14
+ "impl": "ud.UniversalDependenciesCausalPipeline",
15
+ "pt": "AutoModelForTokenClassification"
16
+ }
17
+ },
18
+ "eos_token_id": 2,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 2048,
21
+ "id2label": {
22
+ "0": "ADJ",
23
+ "1": "ADJ|l-acl",
24
+ "2": "ADJ|l-advcl",
25
+ "3": "ADJ|l-amod",
26
+ "4": "ADJ|l-ccomp",
27
+ "5": "ADJ|l-csubj",
28
+ "6": "ADJ|l-csubj:outer",
29
+ "7": "ADJ|l-nmod",
30
+ "8": "ADJ|l-nsubj",
31
+ "9": "ADJ|l-obj",
32
+ "10": "ADJ|l-obl",
33
+ "11": "ADJ|r-acl",
34
+ "12": "ADJ|r-amod",
35
+ "13": "ADJ|r-dep",
36
+ "14": "ADJ|root",
37
+ "15": "ADP",
38
+ "16": "ADP|l-case",
39
+ "17": "ADP|r-case",
40
+ "18": "ADP|r-fixed",
41
+ "19": "ADV",
42
+ "20": "ADV|l-advcl",
43
+ "21": "ADV|l-advmod",
44
+ "22": "ADV|l-obj",
45
+ "23": "ADV|r-dep",
46
+ "24": "ADV|root",
47
+ "25": "AUX",
48
+ "26": "AUX|Polarity=Neg",
49
+ "27": "AUX|Polarity=Neg|r-aux",
50
+ "28": "AUX|Polarity=Neg|r-fixed",
51
+ "29": "AUX|r-aux",
52
+ "30": "AUX|r-cop",
53
+ "31": "AUX|r-fixed",
54
+ "32": "AUX|root",
55
+ "33": "B-ADJ",
56
+ "34": "B-ADP",
57
+ "35": "B-ADV",
58
+ "36": "B-AUX",
59
+ "37": "B-AUX|Polarity=Neg",
60
+ "38": "B-CCONJ",
61
+ "39": "B-DET",
62
+ "40": "B-INTJ",
63
+ "41": "B-NOUN",
64
+ "42": "B-NOUN|Polarity=Neg",
65
+ "43": "B-NUM",
66
+ "44": "B-PART",
67
+ "45": "B-PRON",
68
+ "46": "B-PROPN",
69
+ "47": "B-PUNCT",
70
+ "48": "B-SCONJ",
71
+ "49": "B-SYM",
72
+ "50": "B-VERB",
73
+ "51": "B-X",
74
+ "52": "CCONJ",
75
+ "53": "CCONJ|l-cc",
76
+ "54": "CCONJ|r-cc",
77
+ "55": "DET",
78
+ "56": "DET|l-det",
79
+ "57": "I-ADJ",
80
+ "58": "I-ADP",
81
+ "59": "I-ADV",
82
+ "60": "I-AUX",
83
+ "61": "I-AUX|Polarity=Neg",
84
+ "62": "I-CCONJ",
85
+ "63": "I-DET",
86
+ "64": "I-INTJ",
87
+ "65": "I-NOUN",
88
+ "66": "I-NOUN|Polarity=Neg",
89
+ "67": "I-NUM",
90
+ "68": "I-PART",
91
+ "69": "I-PRON",
92
+ "70": "I-PROPN",
93
+ "71": "I-PUNCT",
94
+ "72": "I-SCONJ",
95
+ "73": "I-SYM",
96
+ "74": "I-VERB",
97
+ "75": "I-X",
98
+ "76": "INTJ",
99
+ "77": "INTJ|l-discourse",
100
+ "78": "INTJ|r-discourse",
101
+ "79": "INTJ|root",
102
+ "80": "NOUN",
103
+ "81": "NOUN|Polarity=Neg",
104
+ "82": "NOUN|Polarity=Neg|l-obl",
105
+ "83": "NOUN|Polarity=Neg|root",
106
+ "84": "NOUN|l-acl",
107
+ "85": "NOUN|l-advcl",
108
+ "86": "NOUN|l-ccomp",
109
+ "87": "NOUN|l-compound",
110
+ "88": "NOUN|l-csubj",
111
+ "89": "NOUN|l-csubj:outer",
112
+ "90": "NOUN|l-nmod",
113
+ "91": "NOUN|l-nsubj",
114
+ "92": "NOUN|l-nsubj:outer",
115
+ "93": "NOUN|l-obj",
116
+ "94": "NOUN|l-obl",
117
+ "95": "NOUN|r-compound",
118
+ "96": "NOUN|r-nmod",
119
+ "97": "NOUN|r-nsubj",
120
+ "98": "NOUN|root",
121
+ "99": "NUM",
122
+ "100": "NUM|l-advcl",
123
+ "101": "NUM|l-compound",
124
+ "102": "NUM|l-nmod",
125
+ "103": "NUM|l-nsubj",
126
+ "104": "NUM|l-nsubj:outer",
127
+ "105": "NUM|l-nummod",
128
+ "106": "NUM|l-obj",
129
+ "107": "NUM|l-obl",
130
+ "108": "NUM|r-compound",
131
+ "109": "NUM|root",
132
+ "110": "PART",
133
+ "111": "PART|l-mark",
134
+ "112": "PART|r-mark",
135
+ "113": "PRON",
136
+ "114": "PRON|l-acl",
137
+ "115": "PRON|l-advcl",
138
+ "116": "PRON|l-nmod",
139
+ "117": "PRON|l-nsubj",
140
+ "118": "PRON|l-nsubj:outer",
141
+ "119": "PRON|l-obj",
142
+ "120": "PRON|l-obl",
143
+ "121": "PRON|root",
144
+ "122": "PROPN",
145
+ "123": "PROPN|l-acl",
146
+ "124": "PROPN|l-advcl",
147
+ "125": "PROPN|l-compound",
148
+ "126": "PROPN|l-nmod",
149
+ "127": "PROPN|l-nsubj",
150
+ "128": "PROPN|l-nsubj:outer",
151
+ "129": "PROPN|l-obj",
152
+ "130": "PROPN|l-obl",
153
+ "131": "PROPN|r-compound",
154
+ "132": "PROPN|r-nmod",
155
+ "133": "PROPN|root",
156
+ "134": "PUNCT",
157
+ "135": "PUNCT|l-punct",
158
+ "136": "PUNCT|r-punct",
159
+ "137": "SCONJ",
160
+ "138": "SCONJ|l-dep",
161
+ "139": "SCONJ|r-fixed",
162
+ "140": "SCONJ|r-mark",
163
+ "141": "SYM",
164
+ "142": "SYM|l-compound",
165
+ "143": "SYM|l-dep",
166
+ "144": "SYM|l-nmod",
167
+ "145": "SYM|l-obl",
168
+ "146": "SYM|r-compound",
169
+ "147": "SYM|r-dep",
170
+ "148": "VERB",
171
+ "149": "VERB|l-acl",
172
+ "150": "VERB|l-advcl",
173
+ "151": "VERB|l-ccomp",
174
+ "152": "VERB|l-compound",
175
+ "153": "VERB|l-csubj",
176
+ "154": "VERB|l-csubj:outer",
177
+ "155": "VERB|l-nmod",
178
+ "156": "VERB|l-obj",
179
+ "157": "VERB|l-obl",
180
+ "158": "VERB|r-acl",
181
+ "159": "VERB|r-advcl",
182
+ "160": "VERB|r-compound",
183
+ "161": "VERB|root",
184
+ "162": "X",
185
+ "163": "X|l-nmod",
186
+ "164": "X|r-dep"
187
+ },
188
+ "initializer_range": 0.02,
189
+ "intermediate_size": 5632,
190
+ "label2id": {
191
+ "ADJ": 0,
192
+ "ADJ|l-acl": 1,
193
+ "ADJ|l-advcl": 2,
194
+ "ADJ|l-amod": 3,
195
+ "ADJ|l-ccomp": 4,
196
+ "ADJ|l-csubj": 5,
197
+ "ADJ|l-csubj:outer": 6,
198
+ "ADJ|l-nmod": 7,
199
+ "ADJ|l-nsubj": 8,
200
+ "ADJ|l-obj": 9,
201
+ "ADJ|l-obl": 10,
202
+ "ADJ|r-acl": 11,
203
+ "ADJ|r-amod": 12,
204
+ "ADJ|r-dep": 13,
205
+ "ADJ|root": 14,
206
+ "ADP": 15,
207
+ "ADP|l-case": 16,
208
+ "ADP|r-case": 17,
209
+ "ADP|r-fixed": 18,
210
+ "ADV": 19,
211
+ "ADV|l-advcl": 20,
212
+ "ADV|l-advmod": 21,
213
+ "ADV|l-obj": 22,
214
+ "ADV|r-dep": 23,
215
+ "ADV|root": 24,
216
+ "AUX": 25,
217
+ "AUX|Polarity=Neg": 26,
218
+ "AUX|Polarity=Neg|r-aux": 27,
219
+ "AUX|Polarity=Neg|r-fixed": 28,
220
+ "AUX|r-aux": 29,
221
+ "AUX|r-cop": 30,
222
+ "AUX|r-fixed": 31,
223
+ "AUX|root": 32,
224
+ "B-ADJ": 33,
225
+ "B-ADP": 34,
226
+ "B-ADV": 35,
227
+ "B-AUX": 36,
228
+ "B-AUX|Polarity=Neg": 37,
229
+ "B-CCONJ": 38,
230
+ "B-DET": 39,
231
+ "B-INTJ": 40,
232
+ "B-NOUN": 41,
233
+ "B-NOUN|Polarity=Neg": 42,
234
+ "B-NUM": 43,
235
+ "B-PART": 44,
236
+ "B-PRON": 45,
237
+ "B-PROPN": 46,
238
+ "B-PUNCT": 47,
239
+ "B-SCONJ": 48,
240
+ "B-SYM": 49,
241
+ "B-VERB": 50,
242
+ "B-X": 51,
243
+ "CCONJ": 52,
244
+ "CCONJ|l-cc": 53,
245
+ "CCONJ|r-cc": 54,
246
+ "DET": 55,
247
+ "DET|l-det": 56,
248
+ "I-ADJ": 57,
249
+ "I-ADP": 58,
250
+ "I-ADV": 59,
251
+ "I-AUX": 60,
252
+ "I-AUX|Polarity=Neg": 61,
253
+ "I-CCONJ": 62,
254
+ "I-DET": 63,
255
+ "I-INTJ": 64,
256
+ "I-NOUN": 65,
257
+ "I-NOUN|Polarity=Neg": 66,
258
+ "I-NUM": 67,
259
+ "I-PART": 68,
260
+ "I-PRON": 69,
261
+ "I-PROPN": 70,
262
+ "I-PUNCT": 71,
263
+ "I-SCONJ": 72,
264
+ "I-SYM": 73,
265
+ "I-VERB": 74,
266
+ "I-X": 75,
267
+ "INTJ": 76,
268
+ "INTJ|l-discourse": 77,
269
+ "INTJ|r-discourse": 78,
270
+ "INTJ|root": 79,
271
+ "NOUN": 80,
272
+ "NOUN|Polarity=Neg": 81,
273
+ "NOUN|Polarity=Neg|l-obl": 82,
274
+ "NOUN|Polarity=Neg|root": 83,
275
+ "NOUN|l-acl": 84,
276
+ "NOUN|l-advcl": 85,
277
+ "NOUN|l-ccomp": 86,
278
+ "NOUN|l-compound": 87,
279
+ "NOUN|l-csubj": 88,
280
+ "NOUN|l-csubj:outer": 89,
281
+ "NOUN|l-nmod": 90,
282
+ "NOUN|l-nsubj": 91,
283
+ "NOUN|l-nsubj:outer": 92,
284
+ "NOUN|l-obj": 93,
285
+ "NOUN|l-obl": 94,
286
+ "NOUN|r-compound": 95,
287
+ "NOUN|r-nmod": 96,
288
+ "NOUN|r-nsubj": 97,
289
+ "NOUN|root": 98,
290
+ "NUM": 99,
291
+ "NUM|l-advcl": 100,
292
+ "NUM|l-compound": 101,
293
+ "NUM|l-nmod": 102,
294
+ "NUM|l-nsubj": 103,
295
+ "NUM|l-nsubj:outer": 104,
296
+ "NUM|l-nummod": 105,
297
+ "NUM|l-obj": 106,
298
+ "NUM|l-obl": 107,
299
+ "NUM|r-compound": 108,
300
+ "NUM|root": 109,
301
+ "PART": 110,
302
+ "PART|l-mark": 111,
303
+ "PART|r-mark": 112,
304
+ "PRON": 113,
305
+ "PRON|l-acl": 114,
306
+ "PRON|l-advcl": 115,
307
+ "PRON|l-nmod": 116,
308
+ "PRON|l-nsubj": 117,
309
+ "PRON|l-nsubj:outer": 118,
310
+ "PRON|l-obj": 119,
311
+ "PRON|l-obl": 120,
312
+ "PRON|root": 121,
313
+ "PROPN": 122,
314
+ "PROPN|l-acl": 123,
315
+ "PROPN|l-advcl": 124,
316
+ "PROPN|l-compound": 125,
317
+ "PROPN|l-nmod": 126,
318
+ "PROPN|l-nsubj": 127,
319
+ "PROPN|l-nsubj:outer": 128,
320
+ "PROPN|l-obj": 129,
321
+ "PROPN|l-obl": 130,
322
+ "PROPN|r-compound": 131,
323
+ "PROPN|r-nmod": 132,
324
+ "PROPN|root": 133,
325
+ "PUNCT": 134,
326
+ "PUNCT|l-punct": 135,
327
+ "PUNCT|r-punct": 136,
328
+ "SCONJ": 137,
329
+ "SCONJ|l-dep": 138,
330
+ "SCONJ|r-fixed": 139,
331
+ "SCONJ|r-mark": 140,
332
+ "SYM": 141,
333
+ "SYM|l-compound": 142,
334
+ "SYM|l-dep": 143,
335
+ "SYM|l-nmod": 144,
336
+ "SYM|l-obl": 145,
337
+ "SYM|r-compound": 146,
338
+ "SYM|r-dep": 147,
339
+ "VERB": 148,
340
+ "VERB|l-acl": 149,
341
+ "VERB|l-advcl": 150,
342
+ "VERB|l-ccomp": 151,
343
+ "VERB|l-compound": 152,
344
+ "VERB|l-csubj": 153,
345
+ "VERB|l-csubj:outer": 154,
346
+ "VERB|l-nmod": 155,
347
+ "VERB|l-obj": 156,
348
+ "VERB|l-obl": 157,
349
+ "VERB|r-acl": 158,
350
+ "VERB|r-advcl": 159,
351
+ "VERB|r-compound": 160,
352
+ "VERB|root": 161,
353
+ "X": 162,
354
+ "X|l-nmod": 163,
355
+ "X|r-dep": 164
356
+ },
357
+ "max_position_embeddings": 2048,
358
+ "mlp_bias": false,
359
+ "model_type": "llama",
360
+ "num_attention_heads": 32,
361
+ "num_hidden_layers": 22,
362
+ "num_key_value_heads": 4,
363
+ "pad_token_id": 0,
364
+ "pretraining_tp": 1,
365
+ "rms_norm_eps": 1e-05,
366
+ "rope_scaling": null,
367
+ "rope_theta": 10000.0,
368
+ "tie_word_embeddings": false,
369
+ "tokenizer_class": "LlamaTokenizerFast",
370
+ "torch_dtype": "float32",
371
+ "transformers_version": "4.42.4",
372
+ "use_cache": true,
373
+ "vocab_size": 32000
374
+ }
maker.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/python3
2
+ src="KoichiYasuoka/karasu-1.1B-upos"
3
+ tgt="KoichiYasuoka/karasu-1.1B-ud-causal"
4
+ url="https://github.com/UniversalDependencies/UD_Japanese-GSDLUW"
5
+ import os
6
+ d=os.path.basename(url)
7
+ os.system("test -d "+d+" || git clone --depth=1 "+url)
8
+ os.system("for F in train dev test ; do cp "+d+"/*-$F.conllu $F.conllu ; done")
9
+ class UDCausalDataset(object):
10
+ def __init__(self,conllu,tokenizer,embeddings=None):
11
+ self.conllu=open(conllu,"r",encoding="utf-8")
12
+ self.tokenizer=tokenizer
13
+ self.embeddings=embeddings
14
+ self.max_tokens=3
15
+ self.seeks=[(0,0)]
16
+ label=set(["SYM"])
17
+ dep=set()
18
+ s=self.conllu.readline()
19
+ while s!="":
20
+ if s=="\n":
21
+ self.seeks.append((self.conllu.tell(),0))
22
+ else:
23
+ w=s.split("\t")
24
+ if len(w)==10:
25
+ if w[0].isdecimal():
26
+ p=w[3] if w[5]=="_" else w[3]+"|"+w[5]
27
+ label.add(p)
28
+ dep.add(p+("|" if w[6]=="0" else "|l-" if int(w[0])<int(w[6]) else "|r-")+w[7])
29
+ self.seeks.append((self.seeks[-1][0],int(w[0])))
30
+ self.max_tokens=max(self.max_tokens,int(w[0])*2+1)
31
+ s=self.conllu.readline()
32
+ lid={}
33
+ for i,l in enumerate(sorted(label)):
34
+ lid[l],lid["B-"+l],lid["I-"+l]=i*3,i*3+1,i*3+2
35
+ for i,d in enumerate(sorted(dep),len(lid)):
36
+ lid[d]=i
37
+ self.label2id=lid
38
+ def __call__(*args):
39
+ lid={l:i for i,l in enumerate(sorted(set(sum([list(t.label2id) for t in args],[]))))}
40
+ for t in args:
41
+ t.label2id=lid
42
+ return lid
43
+ def __del__(self):
44
+ self.conllu.close()
45
+ __len__=lambda self:len(self.seeks)-1
46
+ def __getitem__(self,i):
47
+ s,t=self.seeks[i]
48
+ self.conllu.seek(s)
49
+ form,upos,deps,w=[],[],[],[""]
50
+ while w[0]!="\n":
51
+ w=self.conllu.readline().split("\t")
52
+ if len(w)==10:
53
+ form.append(w[1])
54
+ if w[0].isdecimal():
55
+ upos.append(w[3] if w[5]=="_" else w[3]+"|"+w[5])
56
+ deps.append((int(w[6]),w[7]))
57
+ v=self.tokenizer(form,add_special_tokens=False)
58
+ if t==0:
59
+ i,u=[],[]
60
+ for j,(x,y) in enumerate(zip(v["input_ids"],upos)):
61
+ if x!=[]:
62
+ i+=x
63
+ u+=[y] if len(x)==1 else ["B-"+y]+["I-"+y]*(len(x)-1)
64
+ emb=self.embeddings
65
+ pad=self.tokenizer.pad_token_id
66
+ else:
67
+ import torch
68
+ m=[]
69
+ for x in v["input_ids"]:
70
+ if x==[]:
71
+ m.append(self.embeddings[self.tokenizer.unk_token_id,:])
72
+ else:
73
+ m.append(self.embeddings[x,:].sum(axis=0))
74
+ m.append(self.embeddings[self.tokenizer.sep_token_id,:])
75
+ m.append(self.embeddings[self.tokenizer.pad_token_id,:])
76
+ m.append(self.embeddings[self.tokenizer.cls_token_id,:])
77
+ emb=torch.stack(m)
78
+ i,u=list(range(-1,len(upos)+1)),["SYM"]+upos+["SYM"]
79
+ i.append(t-1)
80
+ k,d=deps[t-1]
81
+ u.append(upos[t-1]+"|"+d if k==0 else upos[t-1])
82
+ for j in range(t,len(upos)):
83
+ i.append(j)
84
+ a,b=deps[j]
85
+ u.append(upos[j]+"|r-"+b if a==t else upos[t-1]+"|l-"+d if j+1==k else upos[j])
86
+ pad=-2
87
+ j=self.max_tokens-len(i)
88
+ if j>0:
89
+ ids=i+[pad]*j
90
+ upos=u+["SYM"]*j
91
+ else:
92
+ ids=i[0:self.max_tokens]
93
+ upos=u[0:self.max_tokens]
94
+ return {"inputs_embeds":emb[ids,:],"labels":[self.label2id[p] for p in upos]}
95
+ from transformers import AutoTokenizer,AutoConfig,LlamaForTokenClassification,DefaultDataCollator,TrainingArguments,Trainer
96
+ tkz=AutoTokenizer.from_pretrained(src)
97
+ trainDS=UDCausalDataset("train.conllu",tkz)
98
+ devDS=UDCausalDataset("dev.conllu",tkz)
99
+ testDS=UDCausalDataset("test.conllu",tkz)
100
+ lid=trainDS(devDS,testDS)
101
+ cfg=AutoConfig.from_pretrained(src,num_labels=len(lid),label2id=lid,id2label={i:l for l,i in lid.items()},ignore_mismatched_sizes=True)
102
+ mdl=LlamaForTokenClassification.from_pretrained(src,config=cfg,ignore_mismatched_sizes=True)
103
+ trainDS.embeddings=mdl.get_input_embeddings().weight
104
+ trainDS.max_tokens=min(trainDS.max_tokens,cfg.max_position_embeddings)
105
+ arg=TrainingArguments(num_train_epochs=3,per_device_train_batch_size=16,dataloader_pin_memory=False,output_dir=tgt,overwrite_output_dir=True,save_total_limit=2,learning_rate=5e-05,warmup_ratio=0.1,save_safetensors=False)
106
+ trn=Trainer(args=arg,data_collator=DefaultDataCollator(),model=mdl,train_dataset=trainDS)
107
+ trn.train()
108
+ trn.save_model(tgt)
109
+ tkz.save_pretrained(tgt)
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e0e3e9027e9a394ddf8e27fe6118f80df198460d1a3cba47416f62d435a6876
3
+ size 4139470066
special_tokens_map.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "pad_token": {
24
+ "content": "</s>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "sep_token": {
31
+ "content": "<s>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "unk_token": {
38
+ "content": "<unk>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ }
44
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "cls_token": "<s>",
34
+ "eos_token": "</s>",
35
+ "legacy": false,
36
+ "model_max_length": 2048,
37
+ "pad_token": "</s>",
38
+ "padding_side": "right",
39
+ "sep_token": "<s>",
40
+ "sp_model_kwargs": {},
41
+ "tokenizer_class": "LlamaTokenizer",
42
+ "unk_token": "<unk>",
43
+ "use_default_system_prompt": false
44
+ }
ud.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy
2
+ from transformers import TokenClassificationPipeline
3
+
4
+ class BellmanFordTokenClassificationPipeline(TokenClassificationPipeline):
5
+ def __init__(self,**kwargs):
6
+ super().__init__(**kwargs)
7
+ x=self.model.config.label2id
8
+ y=[k for k in x if k.startswith("B-") or not (k.startswith("I-") or k.endswith("|root") or k.find("|l-")>0 or k.find("|r-")>0)]
9
+ self.transition=numpy.full((len(x),len(x)),numpy.nan)
10
+ for k,v in x.items():
11
+ for j in ["I-"+k[2:]] if k.startswith("B-") else [k]+y if k.startswith("I-") else y:
12
+ self.transition[v,x[j]]=0
13
+ def check_model_type(self,supported_models):
14
+ pass
15
+ def postprocess(self,model_outputs,**kwargs):
16
+ if "logits" not in model_outputs:
17
+ return self.postprocess(model_outputs[0],**kwargs)
18
+ m=model_outputs["logits"][0].numpy()
19
+ e=numpy.exp(m-numpy.max(m,axis=-1,keepdims=True))
20
+ z=e/e.sum(axis=-1,keepdims=True)
21
+ for i in range(m.shape[0]-1,0,-1):
22
+ m[i-1]+=numpy.nanmax(m[i]+self.transition,axis=1)
23
+ k=[numpy.nanargmax(m[0]+self.transition[0])]
24
+ for i in range(1,m.shape[0]):
25
+ k.append(numpy.nanargmax(m[i]+self.transition[k[-1]]))
26
+ w=[{"entity":self.model.config.id2label[j],"start":s,"end":e,"score":z[i,j]} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
27
+ if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
28
+ for i,t in reversed(list(enumerate(w))):
29
+ p=t.pop("entity")
30
+ if p.startswith("I-"):
31
+ w[i-1]["score"]=min(w[i-1]["score"],t["score"])
32
+ w[i-1]["end"]=w.pop(i)["end"]
33
+ elif p.startswith("B-"):
34
+ t["entity_group"]=p[2:]
35
+ else:
36
+ t["entity_group"]=p
37
+ for t in w:
38
+ t["text"]=model_outputs["sentence"][t["start"]:t["end"]]
39
+ return w
40
+
41
+ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline):
42
+ def __init__(self,**kwargs):
43
+ kwargs["aggregation_strategy"]="simple"
44
+ super().__init__(**kwargs)
45
+ x=self.model.config.label2id
46
+ self.root=numpy.full((len(x)),numpy.nan)
47
+ self.left_arc=numpy.full((len(x)),numpy.nan)
48
+ self.right_arc=numpy.full((len(x)),numpy.nan)
49
+ for k,v in x.items():
50
+ if k.endswith("|root"):
51
+ self.root[v]=0
52
+ elif k.find("|l-")>0:
53
+ self.left_arc[v]=0
54
+ elif k.find("|r-")>0:
55
+ self.right_arc[v]=0
56
+ def postprocess(self,model_outputs,**kwargs):
57
+ import torch
58
+ if "logits" not in model_outputs:
59
+ return self.postprocess(model_outputs[0],**kwargs)
60
+ m=model_outputs["logits"][0].numpy()
61
+ for i in range(m.shape[0]-1,0,-1):
62
+ m[i-1]+=numpy.nanmax(m[i]+self.transition,axis=1)
63
+ k=[numpy.nanargmax(m[0]+self.transition[0])]
64
+ for i in range(1,m.shape[0]):
65
+ k.append(numpy.nanargmax(m[i]+self.transition[k[-1]]))
66
+ w=[{"entity":self.model.config.id2label[j],"start":s,"end":e} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
67
+ for i,t in reversed(list(enumerate(w))):
68
+ p=t.pop("entity")
69
+ if p.startswith("I-"):
70
+ w[i-1]["end"]=max(w.pop(i)["end"],w[i-1]["end"])
71
+ elif i>0 and w[i-1]["end"]>w[i]["start"]:
72
+ w[i-1]["end"]=max(w.pop(i)["end"],w[i-1]["end"])
73
+ elif p.startswith("B-"):
74
+ t["entity_group"]=p[2:]
75
+ else:
76
+ t["entity_group"]=p
77
+ d=[model_outputs["sentence"][t["start"]:t["end"]] for t in w]
78
+ for i in range(len(d)-1,-1,-1):
79
+ if d[i].startswith(" "):
80
+ j=len(d[i])-len(d[i].lstrip())
81
+ d[i]=d[i].lstrip()
82
+ w[i]["start"]+=j
83
+ if d[i].endswith(" "):
84
+ j=len(d[i])-len(d[i].rstrip())
85
+ d[i]=d[i].rstrip()
86
+ w[i]["end"]-=j
87
+ if d[i].strip()=="":
88
+ d.pop(i)
89
+ w.pop(i)
90
+ v=self.tokenizer(d,add_special_tokens=False)
91
+ e=self.model.get_input_embeddings().weight
92
+ m=[]
93
+ for x in v["input_ids"]:
94
+ if x==[]:
95
+ x=[self.tokenizer.unk_token_id]
96
+ m.append(e[x,:].sum(axis=0))
97
+ m.append(e[self.tokenizer.sep_token_id,:])
98
+ m.append(e[self.tokenizer.pad_token_id,:])
99
+ m.append(e[self.tokenizer.cls_token_id,:])
100
+ m=torch.stack(m).to(self.device)
101
+ k=list(range(-1,len(d)+1))
102
+ e=[]
103
+ with torch.no_grad():
104
+ for i in range(len(d)):
105
+ e.append(self.model(inputs_embeds=torch.unsqueeze(m[k+list(range(i,len(d)))+[-2]*i,:],0)).logits[0,-len(d):,:])
106
+ e=torch.stack(e).cpu().numpy()
107
+ for i in range(len(d)):
108
+ for j in range(i):
109
+ e[-j-1,-i-1],e[-i-1,-j-1]=e[-i-1,i-j]+self.left_arc,e[-i-1,i-j]+self.right_arc
110
+ e[-i-1,-i-1]=e[-i-1,0]+self.root
111
+ m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
112
+ h=self.chu_liu_edmonds(m)
113
+ z=[i for i,j in enumerate(h) if i==j]
114
+ if len(z)>1:
115
+ k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
116
+ m[:,z]+=[[0 if j in z and (i!=j or i==k) else h for i in z] for j in range(m.shape[0])]
117
+ h=self.chu_liu_edmonds(m)
118
+ q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
119
+ t=model_outputs["sentence"].replace("\n"," ")
120
+ u="# text = "+t+"\n"
121
+ for i,j in enumerate(d):
122
+ u+="\t".join([str(i+1),j,"_",q[i][0],"_","_" if len(q[i])<3 else "|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),"root" if q[i][-1]=="root" else q[i][-1][2:],"_","_" if i+1<len(d) and w[i]["end"]<w[i+1]["start"] else "SpaceAfter=No"])+"\n"
123
+ return u+"\n"
124
+ def chu_liu_edmonds(self,matrix):
125
+ h=numpy.nanargmax(matrix,axis=0)
126
+ x=[-1 if i==j else j for i,j in enumerate(h)]
127
+ for b in [lambda x,i,j:-1 if i not in x else x[i],lambda x,i,j:-1 if j<0 else x[j]]:
128
+ y=[]
129
+ while x!=y:
130
+ y=list(x)
131
+ for i,j in enumerate(x):
132
+ x[i]=b(x,i,j)
133
+ if max(x)<0:
134
+ return h
135
+ y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
136
+ z=matrix-numpy.nanmax(matrix,axis=0)
137
+ m=numpy.block([[z[x,:][:,x],numpy.nanmax(z[x,:][:,y],axis=1).reshape(len(x),1)],[numpy.nanmax(z[y,:][:,x],axis=0),numpy.nanmax(z[y,y])]])
138
+ k=[j if i==len(x) else x[j] if j<len(x) else y[numpy.nanargmax(z[y,x[i]])] for i,j in enumerate(self.chu_liu_edmonds(m))]
139
+ h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
140
+ i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
141
+ h[i]=x[k[-1]] if k[-1]<len(x) else i
142
+ return h