anitha2520 commited on
Commit
37b0b2a
·
verified ·
1 Parent(s): 126842e

Update model.py

Browse files
Files changed (1) hide show
  1. model.py +27 -41
model.py CHANGED
@@ -3,25 +3,22 @@ from datasets import load_dataset
3
  from unsloth import FastLanguageModel, UnslothTrainer, unsloth_train
4
 
5
  # Load dataset
6
- file_path = "/content/debug_divas_dataset.json" # Ensure the correct file path
7
  dataset = load_dataset("json", data_files=file_path)
8
 
9
  # Load Unsloth's FastLanguageModel and tokenizer
10
- model_name = "unsloth/mistral-7b-instruct" # Using an instruct model for colloquial translation
11
  model, tokenizer = FastLanguageModel.from_pretrained(
12
  model_name=model_name,
13
- max_seq_length=128, # Adjust based on dataset
14
- dtype=torch.float32, # Avoid FP16 issues
15
- load_in_4bit=False, # Disable 4-bit quantization for precision
16
  )
17
 
18
- # Define preprocessing function for colloquial speech
19
  def preprocess_function(examples):
20
- """
21
- Prepares dataset in an informal/colloquial tone for training.
22
- """
23
  inputs = tokenizer(
24
- [f"Convert the given English text into Tamil casual speech: {text}" for text in examples["input"]],
25
  padding="max_length",
26
  truncation=True,
27
  max_length=128,
@@ -32,10 +29,10 @@ def preprocess_function(examples):
32
  inputs["labels"] = labels["input_ids"]
33
  return inputs
34
 
35
- # Apply preprocessing
36
  tokenized_datasets = dataset.map(preprocess_function, batched=True, remove_columns=dataset["train"].column_names)
37
 
38
- # Split dataset into training & testing sets
39
  split_datasets = tokenized_datasets["train"].train_test_split(test_size=0.2, seed=42)
40
  train_dataset, test_dataset = split_datasets["train"], split_datasets["test"]
41
 
@@ -48,11 +45,11 @@ trainer = UnslothTrainer(
48
  args={
49
  "per_device_train_batch_size": 8,
50
  "per_device_eval_batch_size": 8,
51
- "num_train_epochs": 5, # Increased for better colloquial adaptation
52
  "learning_rate": 2e-5,
53
  "save_strategy": "epoch",
54
  "evaluation_strategy": "epoch",
55
- "fp16": False, # Avoiding mixed precision
56
  }
57
  )
58
 
@@ -71,34 +68,23 @@ fine_tuned_model, tokenizer = FastLanguageModel.from_pretrained(
71
  load_in_4bit=False,
72
  )
73
 
74
- # Inference with optimized settings
75
  device = "cuda" if torch.cuda.is_available() else "cpu"
76
  fine_tuned_model.to(device)
77
 
78
- def translate_to_colloquial_tamil(english_text):
79
- instruction = "Convert this English sentence into Tamil colloquial speech"
80
- inputs = tokenizer(f"{instruction}: {english_text}", return_tensors="pt").to(device)
81
-
82
- # Generate colloquial Tamil translation
83
- translated_tokens = fine_tuned_model.generate(
84
- **inputs,
85
- max_new_tokens=50, # Limit response length
86
- do_sample=True, # Enable sampling for natural output
87
- top_p=0.95, # Nucleus sampling for more natural phrasing
88
- temperature=0.7, # Adjust creativity
89
- )
90
- return tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
91
-
92
- # Example translations
93
- examples = [
94
- "The pharmacy is near the bus stop.",
95
- "Take this medicine after food.",
96
- "Train tickets for tomorrow are available.",
97
- "Tell me about OOPs in Python?",
98
- "Can we edit a tuple?",
99
- "When will the new software be implemented?",
100
- ]
101
 
102
- for sentence in examples:
103
- print(f"English: {sentence}")
104
- print(f"Colloquial Tamil: {translate_to_colloquial_tamil(sentence)}\n")
 
3
  from unsloth import FastLanguageModel, UnslothTrainer, unsloth_train
4
 
5
  # Load dataset
6
+ file_path = "/content/debug_divas_dataset.json" # Ensure the file path is correct
7
  dataset = load_dataset("json", data_files=file_path)
8
 
9
  # Load Unsloth's FastLanguageModel and tokenizer
10
+ model_name = "unsloth/mistral-7b-instruct" # Ensure it's an instruct model for translation
11
  model, tokenizer = FastLanguageModel.from_pretrained(
12
  model_name=model_name,
13
+ max_seq_length=128,
14
+ dtype=torch.float32, # Use float32 to avoid FP16 issues
15
+ load_in_4bit=False, # Disable 4-bit quantization if not needed
16
  )
17
 
18
+ # Preprocessing function
19
  def preprocess_function(examples):
 
 
 
20
  inputs = tokenizer(
21
+ [f"Translate the following English sentence to colloquial Tamil: {text}" for text in examples["input"]],
22
  padding="max_length",
23
  truncation=True,
24
  max_length=128,
 
29
  inputs["labels"] = labels["input_ids"]
30
  return inputs
31
 
32
+ # Tokenize dataset
33
  tokenized_datasets = dataset.map(preprocess_function, batched=True, remove_columns=dataset["train"].column_names)
34
 
35
+ # Split dataset
36
  split_datasets = tokenized_datasets["train"].train_test_split(test_size=0.2, seed=42)
37
  train_dataset, test_dataset = split_datasets["train"], split_datasets["test"]
38
 
 
45
  args={
46
  "per_device_train_batch_size": 8,
47
  "per_device_eval_batch_size": 8,
48
+ "num_train_epochs": 3,
49
  "learning_rate": 2e-5,
50
  "save_strategy": "epoch",
51
  "evaluation_strategy": "epoch",
52
+ "fp16": False, # Disable mixed precision training
53
  }
54
  )
55
 
 
68
  load_in_4bit=False,
69
  )
70
 
71
+ # Move model to device
72
  device = "cuda" if torch.cuda.is_available() else "cpu"
73
  fine_tuned_model.to(device)
74
 
75
+ # User input loop for real-time translation
76
+ print("Colloquial Tamil Translator (Type 'exit' to quit)")
77
+ while True:
78
+ input_text = input("Enter an English sentence: ")
79
+ if input_text.lower() == "exit":
80
+ break
81
+
82
+ instruction = "Translate the following English sentence to colloquial Tamil"
83
+
84
+ inputs = tokenizer(f"{instruction}: {input_text}", return_tensors="pt").to(device)
85
+
86
+ # Generate translation
87
+ translated_tokens = fine_tuned_model.generate(**inputs)
88
+ translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
89
 
90
+ print("Colloquial Tamil Translation:", translated_text)