# Slow inference for translation

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fslow-inference-for-translation%2F83063%3E%5C
**Category:** Beginners\
**Created:** [April 22, 2024, 8:41am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fslow-inference-for-translation%2F83063 "2024-04-22T08:41:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![stdb](https://avatars.discourse-cdn.com/v4/letter/s/ea5d25/32.png) [@stdb](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fstdb)%5C
**Post date:** [April 22, 2024, 8:41am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fslow-inference-for-translation%2F83063%2F1 "2024-04-22T08:41:45Z")

</div>

Hello there!  
I am new to using pretrained models. I am having 2.000.000 texts i want to backtranslate. The problem I am having is that it is really slowe (400 Hours plus). I am using an Nvidia rtx 4080 super oc. Here is the code I am using:

import torch  
from transformers import MarianTokenizer, MarianMTModel  
from torch.cuda.amp import autocast  
from tqdm import tqdm

# Setup Marian models for forward and backward translation

source\_lang = ‘en’  
target\_lang = ‘de’  
device = ‘cuda’

model\_name\_f = f’Helsinki-NLP/opus-mt-{source\_lang}-{target\_lang}’  
model\_name\_b = f’Helsinki-NLP/opus-mt-{target\_lang}-{source\_lang}’

tokenizer\_f = MarianTokenizer.from\_pretrained(model\_name\_f)  
model\_f = MarianMTModel.from\_pretrained(model\_name\_f).to(device)

tokenizer\_b = MarianTokenizer.from\_pretrained(model\_name\_b)  
model\_b = MarianMTModel.from\_pretrained(model\_name\_b).to(device)

def translate(tokens, model, batch\_size, tokenizer, desc=‘Translating’):  
all\_generated\_tokens =   
total\_batches = (tokens[‘input\_ids’].size(0) + batch\_size - 1) // batch\_size

```
for i in tqdm(range(0, tokens['input_ids'].size(0), batch_size), total=total_batches, desc=desc):
    batch_tokens = {key: val[i:i+batch_size] for key, val in tokens.items()}
    with autocast():
        with torch.no_grad():
            generated_tokens = model.generate(**batch_tokens)
            all_generated_tokens.append(generated_tokens)

all_generated_tokens = torch.cat(all_generated_tokens)
translated_texts = tokenizer.batch_decode(all_generated_tokens, skip_special_tokens=True)

return translated_texts

```

def batch\_back\_translate(texts, tokenizer\_f, model\_f, tokenizer\_b, model\_b, batch\_size=64):  
# Tokenize all original texts with progress  
print(‘Tokenizing original text…’)  
n\_texts = len(texts)  
tokens\_f = tokenizer\_f(texts, return\_tensors=‘pt’, padding=True, truncation=True, max\_length=256).to(device)  
print(f’Tokenization complete for {n\_texts} texts.')

```
translated_f = translate(tokens_f, model_f, batch_size, tokenizer_f, desc='Forward Translating')

print('Tokenizing translated text...')
tokens_b = tokenizer_b(translated_f, return_tensors='pt', padding=True, truncation=True, max_length=256).to(device)
print(f'Tokenization complete for {len(translated_f)} translated texts.')

translated_b = translate(tokens_b, model_b, batch_size, tokenizer_b, 'Back Translating')

return translated_b

```

_emphasized text_

I am sorry about the formating, I do not know how to get the code in a nice format. Hopefully you can see if anything is wrong or can be improved
