kuyesu22 commited on
Commit
b2e8f4f
·
verified ·
1 Parent(s): d5bd6e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -48
app.py CHANGED
@@ -1,60 +1,70 @@
1
- import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM
3
- from huggingface_hub import login
4
- from peft import PeftModel
5
  import torch
 
 
 
6
  import os
 
7
 
8
  # Login to Hugging Face Hub
9
  access_token = os.environ.get("HUGGING_FACE_HUB_TOKEN")
10
  login(token=access_token)
11
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Load model and tokenizer from the Hugging Face Hub
14
- model_name = "kuyesu22/sunbird-ug-lang-v1.0-llama-2-7b-hf-lora"
15
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
16
- model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
17
- model = PeftModel.from_pretrained(model, model_name)
18
 
19
- # Ensure the model is in evaluation mode
20
  model.eval()
21
 
22
- # Define the translation function
23
- def translate(text, source_lang="Runyankole", target_lang="English"):
24
- prompt = f"Translate from {source_lang} to {target_lang}: {text}"
25
- inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
26
-
 
 
27
  with torch.no_grad():
28
- outputs = model.generate(
29
- inputs["input_ids"],
30
- max_length=100,
31
- num_beams=5,
32
- early_stopping=True
33
- )
34
-
35
- translation = tokenizer.decode(outputs[0], skip_special_tokens=True)
36
- return translation
37
-
38
- # Set up the Gradio interface
39
- def runyankole_to_english(text):
40
- return translate(text, source_lang="Runyankole", target_lang="English")
41
-
42
- def english_to_runyankole(text):
43
- return translate(text, source_lang="English", target_lang="Runyankole")
44
-
45
- # Create Gradio inputs and interface
46
- with gr.Blocks() as demo:
47
- gr.Markdown("# Runyankole-English Translation Model")
48
-
49
- with gr.Tab("Runyankole to English"):
50
- runyankole_input = gr.Textbox(label="Enter Runyankole Text")
51
- english_output = gr.Textbox(label="English Translation")
52
- gr.Button("Translate").click(runyankole_to_english, inputs=runyankole_input, outputs=english_output)
53
-
54
- with gr.Tab("English to Runyankole"):
55
- english_input = gr.components.Textbox(label="Enter English Text")
56
- runyankole_output = gr.components.Textbox(label="Runyankole Translation")
57
- gr.Button("Translate").click(english_to_runyankole, inputs=english_input, outputs=runyankole_output)
58
-
59
- # Launch the app
60
- demo.launch()
 
 
 
 
 
1
  import torch
2
+ from peft import PeftModel, PeftConfig
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from huggingface_hub import login
5
  import os
6
+ import gradio as gr
7
 
8
  # Login to Hugging Face Hub
9
  access_token = os.environ.get("HUGGING_FACE_HUB_TOKEN")
10
  login(token=access_token)
11
 
12
+ # Define model details
13
+ peft_model_id = "kuyesu22/sunbird-ug-lang-v1.0-llama-2-7b-hf-lora" # Update with the correct ID for your fine-tuned Llama 2 model
14
+ config = PeftConfig.from_pretrained(peft_model_id)
15
+
16
+ # Load base model and tokenizer
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ config.base_model_name_or_path,
19
+ torch_dtype=torch.float16, # Mixed precision for faster inference
20
+ device_map="auto", # Automatically allocate to available devices
21
+ offload_folder="./offload" # Directory for offloading layers if needed
22
+ )
23
+ tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
24
 
25
+ # Load the LoRA fine-tuned model
26
+ model = PeftModel.from_pretrained(model, peft_model_id)
 
 
 
27
 
28
+ # Set model to evaluation mode
29
  model.eval()
30
 
31
+ # Define the inference function for translation
32
+ def make_inference(english_text):
33
+ # Format the prompt based on the language pair
34
+ prompt = f"### English:\n{english_text}\n\n### Runyankole:"
35
+ batch = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(model.device)
36
+
37
+ # Generate the translation
38
  with torch.no_grad():
39
+ with torch.cuda.amp.autocast(): # Mixed precision inference for speed
40
+ output_tokens = model.generate(
41
+ input_ids=batch["input_ids"],
42
+ attention_mask=batch["attention_mask"],
43
+ max_new_tokens=100,
44
+ do_sample=True,
45
+ temperature=0.7,
46
+ num_return_sequences=1,
47
+ pad_token_id=tokenizer.eos_token_id
48
+ )
49
+
50
+ # Decode the generated tokens to obtain the translation
51
+ translated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
52
+ return translated_text
53
+
54
+ # Gradio Interface
55
+ def launch_gradio_interface():
56
+ inputs = gr.components.Textbox(lines=2, label="English Text") # Input text in English
57
+ outputs = gr.components.Textbox(label="Translated Runyankole Text") # Output in Runyankole
58
+
59
+ # Launch Gradio app
60
+ gr.Interface(
61
+ fn=make_inference,
62
+ inputs=inputs,
63
+ outputs=outputs,
64
+ title="Sunbird UG Lang Translator",
65
+ description="Translate English to Runyankole using Llama 2 model fine-tuned with LoRA.",
66
+ ).launch()
67
+
68
+ # Entry point to run the Gradio app
69
+ if __name__ == "__main__":
70
+ launch_gradio_interface()