Views
No views yet
google/gemma-2b model for English-to-Sinhala translation.google/gemma-2b model using the Programmer-RD-AI/sinhala-english-singlish-translation dataset from Hugging Face. It was fine-tuned using PEFT and QLoRA for efficient training on a single GPU.1from transformers import AutoModelForCausalLM, AutoTokenizer
2from peft import PeftModel
3import torch
4
5# Define the model ID on the Hugging Face Hub
6model_id = "google/gemma-2b"
7peft_model_id = "AI-Manith/manith-gemma-sinhala-gpt"
8
9# Load the base model
10base_model = AutoModelForCausalLM.from_pretrained(
11 model_id,
12 torch_dtype=torch.bfloat16,
13 device_map="auto",
14)
15
16# Load the tokenizer
17tokenizer = AutoTokenizer.from_pretrained(model_id)
18
19# Load the LoRA adapters and merge them with the base model
20model = PeftModel.from_pretrained(base_model, peft_model_id)
21model = model.merge_and_unload() # Merge LoRA layers and unload the adapter
22
23# Ensure the model is in evaluation mode
24model.eval()
25
26# Define the translation function
27def translate_from_hub(english_text):
28 """This function takes an English sentence and returns the Sinhala translation using the model from the Hub."""
29 instruction = "Translate the following English text to Sinhala."
30 prompt_text = f"""### INSTRUCTION:
31{instruction}
32
33### INPUT:
34{english_text}
35
36### RESPONSE:
37"""
38
39 # Tokenize the input
40 inputs = tokenizer(prompt_text, return_tensors="pt").to("cuda")
41
42 # Generate the response
43 with torch.no_grad(): # Disable gradient calculation for inference
44 outputs = model.generate(**inputs, max_new_tokens=100)
45
46 # Decode the output and extract just the response part
47 decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
48 response_part = decoded_output.split("### RESPONSE:")[1].strip()
49
50 return response_part
51
52# --- Test Cases --- #
53print("\n--- Testing the Translator from Hub ---")
54
55test_sentence_1 = "How are you doing today?"
56translation_1 = translate_from_hub(test_sentence_1)
57print(f"English: {test_sentence_1}")
58print(f"Sinhala: {translation_1}")
59
60print("---")
61
62test_sentence_2 = "Can you translate this sentence?"
63translation_2 = translate_from_hub(test_sentence_2)
64print(f"English: {test_sentence_2}")
65print(f"Sinhala: {translation_2}")