Update README.md
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364---language:- tr- fi- ko- hu- et- kk- ja- multilinguallicense: mitlibrary_name: transformerstags:- translation- seq2seq- mbart-50- morphology- agglutinative- coling2027- nlppipeline_tag: translation---# MorphBART: Intra-Word Structural Biases for Agglutinative Neural Machine TranslationThis is the **MorphBART-Base** foundation checkpoint, integrating vocabulary-preserving intra-word inductive biases directly into the **mBART-50** (`facebook/mbart-large-50-many-to-many-mmt`) architecture.MorphBART is specifically engineered to resolve subword fragmentation and morphological hallucinations when translating from rich agglutinative languages (Turkic, Uralic, Koreanic, Dravidian, etc.) into English and other languages.## 🌟 Architectural Features- **GPU BMES Boundary Extractor:** Dynamically derives Begin, Middle, End, and Single morpheme positions directly from subword tokens.- **Adaptive Boundary-Token Fusion:** Learns continuous boundary representations and injects them via gated residual projection (+2.11M params / +0.34% parameter overhead).- **Intra-Word Morphological Attention (IWMA):** Directly modulates early encoder self-attention matrices (layers 0 & 1) with an intra-word structural reward lpha = 0.5.---## 🚀 Downstream Quickstart: How to Train on Your DataAnyone can load this checkpoint to fine-tune on their agglutinative language translation datasets (e.g., Turkish ightarrow English, Finnish ightarrow English, Korean ightarrow English, Hungarian ightarrow English):```pythonimport torchfrom transformers import AutoTokenizer, MBartForConditionalGeneration, Seq2SeqTrainer, Seq2SeqTrainingArgumentsfrom huggingface_hub import hf_hub_downloadimport json, os# 1. Load Tokenizer & Base Checkpointmodel_name = "NIRVLab/MorphBART-base"tokenizer = AutoTokenizer.from_pretrained(model_name, src_lang="tr_TR", tgt_lang="en_XX")# 2. Load MorphBART (or use the MorphBARTForConditionalGeneration wrapper class)# See notebooks in the MorphBART repository for the end-to-end training pipeline.```## 📖 CitationIf you find MorphBART useful in your research, please cite our paper:```bibtex@inproceedings{morphbart2027,title = {When Morphology Hides in Flat Attention: Intra-Word Structural Biases for Agglutinative Neural Machine Translation},author = {Anonymous},booktitle = {Proceedings of the 31st International Conference on Computational Linguistics (COLING)},year = {2027}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186---language:- multilingual- tr- fi- ko- ja- az- kk- et- mn- ka- ta- te- ml- sw- xh- ru- pl- cs- uk- en- vi- zh- id- fr- es- detags:- mbart-50- morphbart- morphology- agglutinative- seq2seq- machine-translation- coling2027pipeline_tag: translationlicense: mit---# MorphBART-Base: Intra-Word Structural Biases for Agglutinative Neural Machine TranslationMorphBART-Base is a sequence-to-sequence foundation checkpoint designed to mitigate subword fragmentation and morphological hallucination in Neural Machine Translation (NMT). It introduces vocabulary-preserving morphological inductive biases directly into the pretrained encoder of [facebook/mbart-large-50-many-to-many-mmt](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt).Standard multilingual Transformers process statistical subwords via uniform self-attention, ignoring orthographic word boundaries and morphological composition. MorphBART enforces intra-word structural cohesion and boundary-aware representation learning in the early encoder layers without altering the underlying SentencePiece vocabulary or pretrained weights.---## Intended Use and Typological ScopeMorphBART is engineered primarily for translation scenarios from **morphologically rich and agglutinative source languages ($X$)** into **isolating or analytic target languages ($Y$)**:$$\text{Agglutinative / Synthetic } (X) \longrightarrow \text{Isolating / Analytic } (Y)$$### Recommended Source Languages ($X$)The model's architectural priors provide the highest utility on languages characterized by productive affixation, synthetic inflection, and high morpheme-per-word ratios:- **Turkic Family:** Turkish (`tr_TR`), Azerbaijani (`az_AZ`), Kazakh (`kk_KZ`)- **Uralic Family:** Finnish (`fi_FI`), Estonian (`et_EE`)- **Koreanic and Japonic:** Korean (`ko_KR`), Japanese (`ja_XX`)- **Dravidian Family:** Tamil (`ta_IN`), Telugu (`te_IN`), Malayalam (`ml_IN`)- **Mongolic and Kartvelian:** Mongolian (`mn_MN`), Georgian (`ka_GE`)- **Bantu Family:** Swahili (`sw_KE`), Xhosa (`xh_ZA`)- **Synthetic Slavic / Baltic:** Russian (`ru_RU`), Polish (`pl_PL`), Czech (`cs_CZ`), Ukrainian (`uk_UA`)### Recommended Target Languages ($Y$)- **Analytic / Isolating:** English (`en_XX`), Vietnamese (`vi_VN`), Chinese (`zh_CN`), Indonesian (`id_ID`), French (`fr_XX`), Spanish (`es_XX`), German (`de_DE`).**Linguistic Rationale:** In agglutinative languages, grammatical markers (tense, aspect, modality, voice, negation, and case) are concatenated sequentially onto stems. When tokenizers split these words into arbitrary fragments, standard attention often decouples affixes from roots. MorphBART constrains early representations to preserve morphemic envelopes, preventing grammatical inversion and inflectional omissions in the translated output.---## Architectural SpecificationMorphBART adds an exact parameter overhead of only **$+0.34\%$** ($+2.11\text{M}$ parameters over the $611\text{M}$ backbone) with negligible inference overhead:1. **Fast GPU BMES Boundary Extractor:** Directly processes SentencePiece token indices on GPU via vectorized prefix scans to derive Begin ($\text{B}$), Middle ($\text{M}$), End ($\text{E}$), and Single ($\text{S}$) morpheme states in $O(\log T)$ parallel step depth.2. **Adaptive Boundary-Token Fusion:** Learns continuous boundary representations ($E_{\text{bmes}} \in \mathbb{R}^{6 \times 1024}$) and dynamically injects them into subword embeddings through a conservative gated residual projection ($\beta_g = -2.5$).3. **Intra-Word Morphological Attention (IWMA):** Modulates scaled dot-product attention logits with a structural reward ($\alpha = 0.5$) strictly within early encoder layers ($1\text{--}2$):$$S_{ij} = \frac{Q_i K_j^T}{\sqrt{d_k}} + \alpha \cdot M_{ij}$$where $M_{ij} \in \{0, 1\}$ indicates whether tokens $i$ and $j$ belong to the same orthographic word envelope.---## Usage### Loading Checkpoint and InferenceThe checkpoint can be initialized using the wrapper implementation from the official repository:```pythonimport torchfrom transformers import AutoTokenizerfrom src.models.morph_bart import MorphBARTForConditionalGenerationmodel_id = "NIRVLab/MorphBART-base"device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else torch.float32# Load tokenizer and backbone wrappertokenizer = AutoTokenizer.from_pretrained(model_id, src_lang="tr_TR", tgt_lang="en_XX")model = MorphBARTForConditionalGeneration.from_pretrained(model_id,tokenizer=tokenizer,torch_dtype=dtype).to(device)# Example: Turkish to Englishinput_text = "Bu yöntem morfolojik yapıları daha başarılı bir şekilde öğrenir."inputs = tokenizer(input_text, return_tensors="pt").to(device)with torch.no_grad():generated_ids = model.generate(inputs.input_ids,forced_bos_token_id=tokenizer.convert_tokens_to_ids("en_XX"),max_length=64,num_beams=4)translation = tokenizer.decode(generated_ids[0], skip_special_tokens=True)print(translation)```---## Downstream Fine-Tuning### To adapt this base checkpoint to specific agglutinative-to-analytic language pairs, use the standard Hugging Face Seq2SeqTrainer:```pythonimport torchfrom transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments, DataCollatorForSeq2Seqtraining_args = Seq2SeqTrainingArguments(output_dir="./checkpoints/morphbart-finetuned",num_train_epochs=5,per_device_train_batch_size=32,gradient_accumulation_steps=8,learning_rate=2e-5,warmup_ratio=0.06,weight_decay=0.01,label_smoothing_factor=0.1,bf16=torch.cuda.is_available() and torch.cuda.is_bf16_supported(),save_strategy="epoch",evaluation_strategy="epoch",save_total_limit=1,predict_with_generate=True,report_to="none")trainer = Seq2SeqTrainer(model=model,args=training_args,train_dataset=tokenized_train,eval_dataset=tokenized_eval,processing_class=tokenizer,data_collator=DataCollatorForSeq2Seq(tokenizer, model=model.model, pad_to_multiple_of=8))trainer.train()trainer.save_model("./checkpoints/morphbart-finetuned")```---## Benchmark ResultsFine-tuning results on established academic benchmarks demonstrate consistent, statistically significant improvements ($p < 0.001$) over standard mBART-50 fine-tuning:| Language Pair | Benchmark | Domain | Baseline (BLEU / chrF++) | MorphBART (BLEU / chrF++) | Absolute Gain ($\Delta$) ||---|---|---|---:|---:|---:|| Turkish $\rightarrow$ English | OPUS-100 | Web Crawl | $23.05$ / $41.83$ | $24.13$ / $43.06$ | $+1.08$ / $+1.23$ || Turkish $\rightarrow$ English | FLORES-200 | News / Wiki | $29.98$ / $55.22$ | $30.43$ / $56.01$ | $+0.45$ / $+0.79$ || Turkish $\rightarrow$ English | Tatoeba | Conversational | $44.17$ / $60.58$ | $45.37$ / $61.76$ | $+1.20$ / $+1.18$ || Finnish $\rightarrow$ English | OPUS-100 | Web Crawl | $22.14$ / $42.05$ | $23.11$ / $43.12$ | $+0.97$ / $+1.07$ || Finnish $\rightarrow$ English | FLORES-200 | News / Wiki | $26.85$ / $54.12$ | $27.32$ / $54.78$ | $+0.47$ / $+0.66$ |---## Citation```bibtex@article{tang2020multilingual,title = {Multilingual Translation with Extensible Multilingual Pretraining and Finetuning},author = {Tang, Yuqing and Tran, Chau and Li, Xian and Chen, Peng-Jen and Goyal, Naman and Chaudhary, Vishrav and Gu, Jiatao and Fan, Angela},journal = {arXiv preprint arXiv:2008.00401},year = {2020}}```
README.md+155-33