Views
No views yet
1import torch
2from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
3from IndicTransToolkit.processor import IndicProcessor
4# recommended to run this on a gpu with flash_attn installed
5# don't set attn_implemetation if you don't have flash_attn
6DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
7
8src_lang, tgt_lang = "eng_Latn", "hin_Deva"
9model_name = "ai4bharat/indictrans2-en-indic-dist-200M"
10tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
11
12model = AutoModelForSeq2SeqLM.from_pretrained(
13 model_name,
14 trust_remote_code=True,
15 torch_dtype=torch.float16, # performance might slightly vary for bfloat16
16 attn_implementation="flash_attention_2"
17).to(DEVICE)
18
19ip = IndicProcessor(inference=True)
20
21input_sentences = [
22 "When I was young, I used to go to the park every day.",
23 "We watched a new movie last week, which was very inspiring.",
24 "If you had met me at that time, we would have gone out to eat.",
25 "My friend has invited me to his birthday party, and I will give him a gift.",
26]
27
28batch = ip.preprocess_batch(input_sentences, src_lang=src_lang, tgt_lang=tgt_lang)
29
30# Tokenize the sentences and generate input encodings
31inputs = tokenizer(
32 batch,
33 truncation=True,
34 padding="longest",
35 return_tensors="pt",
36 return_attention_mask=True,
37).to(DEVICE)
38
39# Generate translations using the model
40with torch.no_grad():
41 generated_tokens = model.generate(
42 **inputs,
43 use_cache=True,
44 min_length=0,
45 max_length=256,
46 num_beams=5,
47 num_return_sequences=1,
48 )
49
50# Decode the generated tokens into text
51generated_tokens = tokenizer.batch_decode(
52 generated_tokens,
53 skip_special_tokens=True,
54 clean_up_tokenization_spaces=True,
55)
56
57# Postprocess the translations, including entity replacement
58translations = ip.postprocess_batch(generated_tokens, lang=tgt_lang)
59
60for input_sentence, translation in zip(input_sentences, translations):
61 print(f"{src_lang}: {input_sentence}")
62 print(f"{tgt_lang}: {translation}")model_name parameter. Please read the model card of the RoPE-IT2 models for more information about the generation.flash_attention_2 for efficient generation.@article{gala2023indictrans,
title={IndicTrans2: Towards High-Quality and Accessible Machine Translation Models for all 22 Scheduled Indian Languages},
author={Jay Gala and Pranjal A Chitale and A K Raghavan and Varun Gumma and Sumanth Doddapaneni and Aswanth Kumar M and Janki Atul Nawale and Anupama Sujatha and Ratish Puduppully and Vivek Raghavan and Pratyush Kumar and Mitesh M Khapra and Raj Dabre and Anoop Kunchukuttan},
journal={Transactions on Machine Learning Research},
issn={2835-8856},
year={2023},
url={https://openreview.net/forum?id=vfT4YuzAYA},
note={}
}