# Fine-tuning TrOCR on new language

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%3E%5C
**Category:** 🤗Transformers\
**Created:** [October 12, 2023, 12:44am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234 "2023-10-12T00:44:54Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![magistermilitum](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/magistermilitum/32/20188_2.png) [@magistermilitum](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fmagistermilitum)%5C
**Post date:** [October 12, 2023, 12:44am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%2F1 "2023-10-12T00:44:54Z")

</div>

Hi everyone,

I’m currently fine-tuning TrOCR for ancient handwritten texts in Spanish, utilizing the “microsoft/trocr-large-handwritten” as processor and model, which has yielded outstanding results. However, I’ve been contemplating whether we could achieve even better results by incorporating specific language models. In some discussions, such as the one found here: [Fine tune TrOCR using bert-base-multilingual-cased · Issue #15823 · huggingface/transformers · GitHub](https://github.com/huggingface/transformers/issues/15823), recommendations for training on another language model are like that:

```auto
feature_extractor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-384")
decoder_tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
processor = TrOCRProcessor(feature_extractor=feature_extractor, tokenizer=decoder_tokenizer)

```

Subsequently:

```auto
model = VisionEncoderDecoderModel.from_encoder_decoder_pretrained("google/vit-base-patch16-384", "xlm-roberta-base")

```

However, this approach appears to be more of a “from scratch” training method rather than fine-tuning. What if we wish to leverage the pre-trained weights from the existing powerful TrOCR model for handwriting (“microsoft/trocr-large-handwritten”) in conjunction with a larger model, such as “xlm-roberta-large-finetuned-conll02-spanish” or any other Spanish RoBERTa model? Would this be a viable strategy? If so, what might be an effective combination? Maybe something like this:

```auto
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-large-handwritten")
processor.tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-base")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-large-handwritten")

```

Thank you in advance for your help and insights.

---

<div class="post-metadata">

**Author:** ![Cherryblade29](https://avatars.discourse-cdn.com/v4/letter/c/e95f7d/32.png) [@Cherryblade29](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FCherryblade29)%5C
**Post date:** [August 24, 2024, 1:58pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%2F2 "2024-08-24T13:58:08Z")

</div>

can i ask you ?, how did you do it , explain to me step by step , because i want to fine tune TrOCR on french letters.

---

<div class="post-metadata">

**Author:** ![nielsr](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/nielsr/32/39617_2.png) [@nielsr](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fnielsr)%5C
**Post date:** [August 26, 2024, 2:10pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%2F3 "2024-08-26T14:10:53Z")

</div>

Answered here: [how to fine tune TrOCR on specifique langage guide. · Issue #33106 · huggingface/transformers · GitHub](https://github.com/huggingface/transformers/issues/33106#issuecomment-2310149187)

---

<div class="post-metadata">

**Author:** ![ariiif](https://avatars.discourse-cdn.com/v4/letter/a/3da27b/32.png) [@ariiif](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fariiif)%5C
**Post date:** [April 9, 2025, 3:09pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%2F4 "2025-04-09T15:09:44Z")

</div>

Hi,

I’m fine-tuning a TrOCR model (small printed) on a new language using a minimal subset and conservative training setup. However, I encountered the following error during evaluation:

 ![trocr_err](https://us1.discourse-cdn.com/hellohellohello/original/3X/7/9/7986128752f6e7ad10cca9de3a73964d3d97f29b.png)

When using `predict_with_generate=True`, `pred.predictions` should be the generated token IDs, not logits. However, in my case, `pred.predictions` still contains raw logits of shape `(batch_size, sequence_length, vocab_size)` instead of `(batch_size, sequence_length)`.

Any guidance or clarification on whether this behavior is expected, or how to properly configure the trainer to return generated IDs for TrOCR, would be greatly appreciated!

Thanks in advance! 🙌

---

<div class="post-metadata">

**Author:** ![John6666](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/john6666/32/27664_2.png) [@John6666](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2FJohn6666)%5C
**Post date:** [April 10, 2025, 2:17am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ffine-tuning-trocr-on-new-language%2F58234%2F5 "2025-04-10T02:17:28Z")

</div>

It seems that the error may occur due to the tokenizer settings.

> <https://github.com/huggingface/trl/issues/1073>
>
> The problem happened in trl/trl/trainer /utils.py in line \*\*456\*\*
> \`\`\`
> else:
> … # adapted from https://stackoverflow.com/questions/73256206
> if "prompt" in k:
> to\_pad = \[torch.LongTensor(ex\[k\]\[::-1\]) for ex in batch\]
> else:
> 456 to\_pad = \[torch.LongTensor(ex\[k\]) for ex in batch\]
> if k.endswith("\_input\_ids"):
> padding\_value = self.tokenizer.pad\_token\_id
> \`\`\`
> I am using \*\*\[Qwen/Qwen-1\_8B-Chat\](https://huggingface.co/Qwen/Qwen-1\_8B-Chat)\*\* model and \*\*official finetune.py\*\* to do the DPOTrain.
> My training datasets are like this:
> \> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> {"question": "1+2=", "response\_chosen": "4", "response\_rejected": "3"}
> 
> If I direclty run the DPO code will meet the problem:
> \> File "/data/ketadb/condaenv/envs/qwen/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 678, in \_next\_data
> \> data = self.\_dataset\_fetcher.fetch(index) # may raise StopIteration
> \> File "/data/ketadb/condaenv/envs/qwen/lib/python3.9/site-packages/torch/utils/data/\_utils/fetch.py", line 54, in fetch
> \> return self.collate\_fn(data)
> \> File "/data/ketadb/condaenv/envs/qwen/lib/python3.9/site-packages/trl/trainer/utils.py", line 490, in \_\_call\_\_
> \> return self.collate(tokenized\_batch)
> \> File "/data/ketadb/condaenv/envs/qwen/lib/python3.9/site-packages/trl/trainer/utils.py", line 449, in collate
> \> to\_pad = \[torch.LongTensor(ex\[k\]) for ex in batch\]
> \> File "/data/ketadb/condaenv/envs/qwen/lib/python3.9/site-packages/trl/trainer/utils.py", line 449, in \<listcomp\>
> \> to\_pad = \[torch.LongTensor(ex\[k\]) for ex in batch\]
> \> TypeError: an integer is required (got type NoneType)
> 
> If I debug the code in line 483:
> \`\`\`
> for feature in features:
> prompt = feature\["prompt"\]
> chosen = feature\["chosen"\]
> rejected = feature\["rejected"\]
> 
> 483 batch\_element = self.tokenize\_batch\_element(prompt, chosen, rejected)
> print(batch\_element)
> tokenized\_batch.append(batch\_element)
> \`\`\`
> If I print the batch\_element out, there will be another extra None at the end of the array:
> 
> \> batch\_element:{'chosen\_input\_ids': \[16, 10, 17, 28, 19, None\], 'chosen\_attention\_mask': \[1, 1, 1, 1, 1, 1\], 'chosen\_labels': \[-100, -100, -100, -100, 19, None\], 'rejected\_input\_ids': \[16, 10, 17, 28, 18, None\], 'rejected\_attention\_mask': \[1, 1, 1, 1, 1, 1\], 'rejected\_labels': \[-100, -100, -100, -100, 18, None\], 'prompt\_input\_ids': \[16, 10, 17, 28\], 'prompt\_attention\_mask': \[1, 1, 1, 1\], 'prompt': '1+2=', 'chosen': '1+2=4', 'rejected': '1+2=3', 'chosen\_response\_only': '4', 'rejected\_response\_only': '3'}
> 
> My chosen\_input\_ids 1+2=4 length should be \*\*5\*\*, but after self.tokenize\_batch\_element the 'chosen\_input\_ids': \[16, 10, 17, 28, 19, None\] length is \*\*6\*\*, and there is another extra \*\*None\*\* lead the \_TypeError: an integer is required (got type NoneType)\_ problem.
> So, I changed the line \`456 to\_pad = \[torch.LongTensor(ex\[k\]) for ex in batch\]\` to \`456 to\_pad = \[torch.LongTensor(ex\[k\]\[:-1\]) for ex in batch\]\` and It worked
> 
> \> {'loss': 0.2599, 'learning\_rate': 0.0003, 'rewards/chosen': 0.0, 'rewards/rejected': 0.0, 'rewards/accuracies': 0.0, 'rewards/margins': 0.0, 'logps/rejected': -0.21053116023540497, 'logps/chosen': -4.585531234741211, 'logits/rejected': -2.686852216720581, 'logits/chosen': -2.6731910705566406, 'epoch': 1.0}
> \> {'loss': 0.2599, 'learning\_rate': 0.00015, 'rewards/chosen': 0.0, 'rewards/rejected': 0.0, 'rewards/accuracies': 0.0, 'rewards/margins': 0.0, 'logps/rejected': -0.21053116023540497, 'logps/chosen': -4.585531234741211, 'logits/rejected': -2.686852216720581, 'logits/chosen': -2.6731910705566406, 'epoch': 2.0}
> \> {'loss': 0.1227, 'learning\_rate': 0.0, 'rewards/chosen': 0.27905863523483276, 'rewards/rejected': -0.17719139158725739, 'rewards/accuracies': 1.0, 'rewards/margins': 0.45625001192092896, 'logps/rejected': -1.9824450016021729, 'logps/chosen': -1.7949450016021729, 'logits/rejected': -2.546565055847168, 'logits/chosen': -2.5510566234588623, 'epoch': 2.67}
> \> {'train\_runtime': 2.826, 'train\_samples\_per\_second': 3.185, 'train\_steps\_per\_second': 1.062, 'train\_loss': 0.2141884664694468, 'epoch': 2.67}
> \> 100%|███████████████████████████████████████████████████████████████████████████████████████████████| 3/3 \[00:02\<00:00, 1.06it/s\]
> \> \*\*\*\*\* train metrics \*\*\*\*\*
> \> epoch = 2.67
> \> train\_loss = 0.2142
> \> train\_runtime = 0:00:02.82
> \> train\_samples = 3
> \> train\_samples\_per\_second = 3.185
> \> train\_steps\_per\_second = 1.062
> \> Training metrics: {'train\_runtime': 2.826, 'train\_samples\_per\_second': 3.185, 'train\_steps\_per\_second': 1.062, 'train\_loss': 0.2141884664694468, 'epoch': 2.67, 'train\_samples': 3}
> 
> I do not know whether am I right, or I did not use it the right way.  
> I think the problem may happened because Qwen has it own tokenizer.
> 
> My prompt dict :
> \`\`\`
> return {
> "prompt": \["Question: " + question + "\\n\\nAnswer: " + for question in examples\["question"\]\],
> "chosen": examples\["response\_chosen"\],
> "rejected": examples\["response\_rejected"\],
> }
> \`\`\`
> DPOTrainer :
> \`\`\`
> trainer = DPOTrainer(
> model,
> ref\_model=deepcopy(model),
> args=training\_args,
> beta=0.1,
> tokenizer=tokenizer,
> peft\_config=lora\_config,
> max\_prompt\_length=training\_args.model\_max\_length,
> max\_length=training\_args.model\_max\_length,
> train\_dataset=data\_module\['train\_dataset'\],
> eval\_dataset=data\_module\['eval\_dataset'\],
> )
> \`\`\`
> tokenizer :
> 
> \`\`\`
> tokenizer = transformers.AutoTokenizer.from\_pretrained(
> model\_args.model\_name\_or\_path,
> cache\_dir=training\_args.cache\_dir,
> model\_max\_length=training\_args.model\_max\_length,
> padding\_side="right",
> use\_fast=False,
> trust\_remote\_code=True,
> )
> tokenizer.pad\_token\_id = tokenizer.eod\_id
> if tokenizer.pad\_token\_id is None:
> tokenizer.pad\_token\_id = 0 # set as the \<unk\> token
> \`\`\`

> [@TypeError: argument 'ids': 'list' object cannot be interpreted as an integer when lora training](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Ftypeerror-argument-ids-list-object-cannot-be-interpreted-as-an-integer-when-lora-training%2F139940%2F9)%3A
>
> hello, i meet the same question," text = self.\_tokenizer.decode(token\_ids, skip\_special\_tokens=skip\_special\_tokens) TypeError: argument ‘ids’: ‘list’ object cannot be interpreted as an integer" i hope it will be helpful. my question is i forget add “for output in batch\_outputs:” rofl //my code is as follows: batch\_outputs = model.generate( input\_ids=prompt\_ids.input\_ids, … ) for output in batch\_outputs: print("output is ",tokenizer.decode(output, skip\_special\_tokens=True))
