KoichiYasuoka commited on
Commit
1cc3d00
1 Parent(s): a7e89b4

initial release

Browse files
Files changed (8) hide show
  1. README.md +27 -0
  2. config.json +0 -0
  3. maker.py +59 -0
  4. pytorch_model.bin +3 -0
  5. special_tokens_map.json +37 -0
  6. tokenizer_config.json +64 -0
  7. ud.py +63 -0
  8. vocab.txt +0 -0
README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - "be"
4
+ tags:
5
+ - "belarusian"
6
+ - "token-classification"
7
+ - "pos"
8
+ - "dependency-parsing"
9
+ datasets:
10
+ - "universal_dependencies"
11
+ license: "cc-by-sa-4.0"
12
+ pipeline_tag: "token-classification"
13
+ ---
14
+
15
+ # roberta-small-belarusian-ud-goeswith
16
+
17
+ ## Model Description
18
+
19
+ This is a RoBERTa model pre-trained on Belarusian texts for POS-tagging and dependency-parsing (using `goeswith` for subwords), derived from [roberta-small-belarusian-upos](https://huggingface.co/KoichiYasuoka/roberta-small-belarusian-upos).
20
+
21
+ ## How to Use
22
+
23
+ ```py
24
+ from transformers import pipeline
25
+ nlp=pipeline("universal-dependencies","KoichiYasuoka/roberta-small-belarusian-ud-goeswith",trust_remote_code=True,aggregation_strategy="simple")
26
+ ```
27
+
config.json ADDED
The diff for this file is too large to render. See raw diff
 
maker.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/python3
2
+ src="KoichiYasuoka/roberta-small-belarusian-upos"
3
+ tgt="KoichiYasuoka/roberta-small-belarusian-ud-goeswith"
4
+ import os
5
+ url="https://github.com/UniversalDependencies/UD_Belarusian-HSE"
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 UDgoeswithDataset(object):
10
+ def __init__(self,conllu,tokenizer):
11
+ self.ids,self.tags,label=[],[],set()
12
+ with open(conllu,"r",encoding="utf-8") as r:
13
+ cls,sep,msk=tokenizer.cls_token_id,tokenizer.sep_token_id,tokenizer.mask_token_id
14
+ dep,c="-|_|dep",[]
15
+ for s in r:
16
+ t=s.split("\t")
17
+ if len(t)==10:
18
+ if t[0].isdecimal():
19
+ c.append(t)
20
+ elif c!=[]:
21
+ v=tokenizer([t[1] for t in c],add_special_tokens=False)["input_ids"]
22
+ for i in range(len(v)-1,-1,-1):
23
+ if len(v[i])==0:
24
+ v[i]=[tokenizer.unk_token_id]
25
+ elif len(v[i])>1:
26
+ for j in range(1,len(v[i])):
27
+ c.insert(i+1,[c[i][0],"_","_","X","_","_",c[i][0],"goeswith","_","_"])
28
+ y=["0"]+[t[0] for t in c]
29
+ h=[i if t[6]=="0" else y.index(t[6]) for i,t in enumerate(c,1)]
30
+ p,v=[t[3]+"|"+t[5]+"|"+t[7] for t in c],sum(v,[])
31
+ if len(v)<tokenizer.model_max_length-3:
32
+ self.ids.append([cls]+v+[sep])
33
+ self.tags.append([dep]+p+[dep])
34
+ label=set(sum([self.tags[-1],list(label)],[]))
35
+ for i,k in enumerate(v):
36
+ self.ids.append([cls]+v[0:i]+[msk]+v[i+1:]+[sep,k])
37
+ self.tags.append([dep]+[t if h[j]==i+1 else dep for j,t in enumerate(p)]+[dep,dep])
38
+ c=[]
39
+ self.label2id={l:i for i,l in enumerate(sorted(label))}
40
+ def __call__(*args):
41
+ label=set(sum([list(t.label2id) for t in args],[]))
42
+ lid={l:i for i,l in enumerate(sorted(label))}
43
+ for t in args:
44
+ t.label2id=lid
45
+ return lid
46
+ __len__=lambda self:len(self.ids)
47
+ __getitem__=lambda self,i:{"input_ids":self.ids[i],"labels":[self.label2id[t] for t in self.tags[i]]}
48
+ from transformers import AutoTokenizer,AutoConfig,AutoModelForTokenClassification,DataCollatorForTokenClassification,TrainingArguments,Trainer
49
+ tkz=AutoTokenizer.from_pretrained(src)
50
+ trainDS=UDgoeswithDataset("train.conllu",tkz)
51
+ devDS=UDgoeswithDataset("dev.conllu",tkz)
52
+ testDS=UDgoeswithDataset("test.conllu",tkz)
53
+ lid=trainDS(devDS,testDS)
54
+ cfg=AutoConfig.from_pretrained(src,num_labels=len(lid),label2id=lid,id2label={i:l for l,i in lid.items()},ignore_mismatched_sizes=True)
55
+ arg=TrainingArguments(num_train_epochs=3,per_device_train_batch_size=48,output_dir="/tmp",overwrite_output_dir=True,save_total_limit=2,evaluation_strategy="epoch",learning_rate=5e-05,warmup_ratio=0.1,save_safetensors=False)
56
+ trn=Trainer(args=arg,data_collator=DataCollatorForTokenClassification(tkz),model=AutoModelForTokenClassification.from_pretrained(src,config=cfg,ignore_mismatched_sizes=True),train_dataset=trainDS,eval_dataset=devDS)
57
+ trn.train()
58
+ trn.save_model(tgt)
59
+ tkz.save_pretrained(tgt)
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b0827682edbb5050271e666f0e0686c9b092a1f0bc51545c7c492d0678f9f1f
3
+ size 67315955
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": true,
48
+ "do_lowercase": false,
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 128,
51
+ "never_split": [
52
+ "[CLS]",
53
+ "[PAD]",
54
+ "[SEP]",
55
+ "[UNK]",
56
+ "[MASK]"
57
+ ],
58
+ "pad_token": "[PAD]",
59
+ "sep_token": "[SEP]",
60
+ "strip_accents": false,
61
+ "tokenize_chinese_chars": true,
62
+ "tokenizer_class": "BertTokenizer",
63
+ "unk_token": "[UNK]"
64
+ }
ud.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TokenClassificationPipeline
2
+
3
+ class UniversalDependenciesPipeline(TokenClassificationPipeline):
4
+ def _forward(self,model_inputs):
5
+ import torch
6
+ v=model_inputs["input_ids"][0].tolist()
7
+ with torch.no_grad():
8
+ e=self.model(input_ids=torch.tensor([v[0:i]+[self.tokenizer.mask_token_id]+v[i+1:]+[j] for i,j in enumerate(v[1:-1],1)],device=self.device))
9
+ return {"logits":e.logits[:,1:-2,:],**model_inputs}
10
+ def postprocess(self,model_outputs,**kwargs):
11
+ import numpy
12
+ if "logits" not in model_outputs:
13
+ return "".join(self.postprocess(x,**kwargs) for x in model_outputs)
14
+ e=model_outputs["logits"].numpy()
15
+ r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
16
+ e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan)
17
+ g=self.model.config.label2id["X|_|goeswith"]
18
+ r=numpy.tri(e.shape[0])
19
+ for i in range(e.shape[0]):
20
+ for j in range(i+2,e.shape[1]):
21
+ r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
22
+ e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
23
+ m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
24
+ h=self.chu_liu_edmonds(m)
25
+ z=[i for i,j in enumerate(h) if i==j]
26
+ if len(z)>1:
27
+ k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
28
+ 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])]
29
+ h=self.chu_liu_edmonds(m)
30
+ v=[(s,e) for s,e in model_outputs["offset_mapping"][0].tolist() if s<e]
31
+ q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
32
+ g="aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none"
33
+ if g:
34
+ for i,j in reversed(list(enumerate(q[1:],1))):
35
+ if j[-1]=="goeswith" and set([t[-1] for t in q[h[i]+1:i+1]])=={"goeswith"}:
36
+ h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
37
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
38
+ q.pop(i)
39
+ t=model_outputs["sentence"].replace("\n"," ")
40
+ u="# text = "+t+"\n"
41
+ for i,(s,e) in enumerate(v):
42
+ u+="\t".join([str(i+1),t[s:e],t[s:e] if g else "_",q[i][0],"_","|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),q[i][-1],"_","_" if i+1<len(v) and e<v[i+1][0] else "SpaceAfter=No"])+"\n"
43
+ return u+"\n"
44
+ def chu_liu_edmonds(self,matrix):
45
+ import numpy
46
+ h=numpy.nanargmax(matrix,axis=0)
47
+ x=[-1 if i==j else j for i,j in enumerate(h)]
48
+ 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]]:
49
+ y=[]
50
+ while x!=y:
51
+ y=list(x)
52
+ for i,j in enumerate(x):
53
+ x[i]=b(x,i,j)
54
+ if max(x)<0:
55
+ return h
56
+ y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
57
+ z=matrix-numpy.nanmax(matrix,axis=0)
58
+ 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])]])
59
+ 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))]
60
+ h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
61
+ i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
62
+ h[i]=x[k[-1]] if k[-1]<len(x) else i
63
+ return h
vocab.txt ADDED
The diff for this file is too large to render. See raw diff