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

Update model.py

Browse files
Files changed (1) hide show
  1. model.py +39 -20
model.py CHANGED
@@ -3,23 +3,25 @@ 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" # Corrected 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" # Ensure it's an instruct model for translation
11
  model, tokenizer = FastLanguageModel.from_pretrained(
12
  model_name=model_name,
13
- max_seq_length=128, # Adjust based on your dataset
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
- # Combine instruction and input for the model
 
 
21
  inputs = tokenizer(
22
- [f"Translate the following English sentence to colloquial Tamil: {text}" for text in examples["input"]],
23
  padding="max_length",
24
  truncation=True,
25
  max_length=128,
@@ -30,10 +32,10 @@ def preprocess_function(examples):
30
  inputs["labels"] = labels["input_ids"]
31
  return inputs
32
 
33
- # Tokenize dataset
34
  tokenized_datasets = dataset.map(preprocess_function, batched=True, remove_columns=dataset["train"].column_names)
35
 
36
- # Split dataset
37
  split_datasets = tokenized_datasets["train"].train_test_split(test_size=0.2, seed=42)
38
  train_dataset, test_dataset = split_datasets["train"], split_datasets["test"]
39
 
@@ -46,11 +48,11 @@ trainer = UnslothTrainer(
46
  args={
47
  "per_device_train_batch_size": 8,
48
  "per_device_eval_batch_size": 8,
49
- "num_train_epochs": 3,
50
  "learning_rate": 2e-5,
51
  "save_strategy": "epoch",
52
  "evaluation_strategy": "epoch",
53
- "fp16": False, # Disable mixed precision training
54
  }
55
  )
56
 
@@ -69,17 +71,34 @@ fine_tuned_model, tokenizer = FastLanguageModel.from_pretrained(
69
  load_in_4bit=False,
70
  )
71
 
72
- # Translation inference
73
  device = "cuda" if torch.cuda.is_available() else "cpu"
74
  fine_tuned_model.to(device)
75
 
76
- input_text = "The pharmacy is near the bus stop."
77
- instruction = "Translate the following English sentence to colloquial Tamil"
 
78
 
79
- inputs = tokenizer(f"{instruction}: {input_text}", return_tensors="pt").to(device)
 
 
 
 
 
 
 
 
80
 
81
- # Generate translation
82
- translated_tokens = fine_tuned_model.generate(**inputs)
83
- translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
 
 
 
 
 
 
84
 
85
- print("Translated Tamil Text:", translated_text)
 
 
 
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
  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
  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
  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")