#! /usr/bin/python3 src="meta-llama/Llama-3.2-1B" tgt="KoichiYasuoka/Llama-3.2-1B-thai-ud-causal" url="https://github.com/KoichiYasuoka/spaCy-Thai" import os d=os.path.basename(url) os.system("test -d "+d+" || git clone --depth=1 "+url) os.system("for F in train dev test ; do cp "+d+"/UD_Thai-Corpora/th_tud-ud-$F.conllu $F.conllu ; done") class UDCausalDataset(object): def __init__(self,conllu,tokenizer,oldtokenizer=None,embeddings=None): self.conllu=open(conllu,"r",encoding="utf-8") self.tokenizer=tokenizer self.oldtokenizer=oldtokenizer if oldtokenizer else tokenizer self.embeddings=embeddings self.max_tokens=3 self.seeks=[(0,0)] label=set(["SYM"]) dep=set() s=self.conllu.readline() while s!="": if s=="\n": self.seeks.append((self.conllu.tell(),0)) else: w=s.split("\t") if len(w)==10: if w[0].isdecimal(): p=w[3] if w[5]=="_" else w[3]+"|"+w[5] label.add(p) dep.add(p+("|" if w[6]=="0" else "|l-" if int(w[0])0: ids=i+[pad]*j upos=u+["SYM"]*j else: ids=i[0:self.max_tokens] upos=u[0:self.max_tokens] return {"inputs_embeds":emb[ids,:],"labels":[self.label2id[p] for p in upos]} from transformers import AutoTokenizer,AutoConfig,AutoModelForTokenClassification,DefaultDataCollator,TrainingArguments,Trainer from tokenizers.pre_tokenizers import Sequence,Split,Whitespace from tokenizers import Regex from copy import deepcopy otk=AutoTokenizer.from_pretrained(src,cls_token="<|begin_of_text|>",sep_token="<|end_of_text|>",pad_token="<|finetune_right_pad_id|>",unk_token="<|python_tag|>") ntk=deepcopy(otk) ntk.backend_tokenizer.pre_tokenizer=Sequence([Whitespace(),Split(Regex("[\u0e40-\u0e44]?[\u0e01-\u0e2e][\u0e30-\u0e3a\u0e45\u0e47-\u0e4e]*|."),"isolated"),otk.backend_tokenizer.pre_tokenizer]) trainDS=UDCausalDataset("train.conllu",ntk,otk) devDS=UDCausalDataset("dev.conllu",ntk,otk) testDS=UDCausalDataset("test.conllu",ntk,otk) lid=trainDS(devDS,testDS) cfg=AutoConfig.from_pretrained(src,num_labels=len(lid),label2id=lid,id2label={i:l for l,i in lid.items()},ignore_mismatched_sizes=True) mdl=AutoModelForTokenClassification.from_pretrained(src,config=cfg,ignore_mismatched_sizes=True) trainDS.embeddings=mdl.get_input_embeddings().weight trainDS.max_tokens=min(trainDS.max_tokens,cfg.max_position_embeddings) 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) trn=Trainer(args=arg,data_collator=DefaultDataCollator(),model=mdl,train_dataset=trainDS) trn.train() trn.save_model(tgt) otk.save_pretrained(tgt)