KoichiYasuoka commited on
Commit
957bf44
1 Parent(s): bbd43af

initial release

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