File size: 13,423 Bytes
a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 8735cdd f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 a1dc6b2 f6c9488 9618fad f6c9488 a1dc6b2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
---
library_name: transformers
tags:
- unsloth
---
### Model Description
<!-- Provide a longer summary of what this model is. -->
This is the model quantized mistral which is trained using 4bit quantization and Qlora using unsloth library on Academic MCQ based dataset. It takes a Context as input and Generate relevant relevant MCQs. It can further go into specific Subjects like Chemistry, Physics, Biology and General Sunject.
You can change instruction to emulate these outputs based on inputs.
## Requirements
```python
!pip install -U xformers --index-url https://download.pytorch.org/whl/cu121
!pip install "unsloth[kaggle-new] @ git+https://github.com/unslothai/unsloth.git"
import os
os.environ["WANDB_DISABLED"] = "true"
```
### Single Inference
```python
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
model_id="DisgustingOzil/Academic-MCQ-Generator"
model = AutoPeftModelForCausalLM.from_pretrained(
model_id, # YOUR MODEL YOU USED FOR TRAINING
load_in_4bit = load_in_4bit,
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
"""
### Response
input2="""Mitosis (/maɪˈtoʊsɪs/) is a part of the cell cycle in which replicated chromosomes are separated into two new nuclei. Cell division by mitosis is an equational division which gives rise to genetically identical cells in which the total number of chromosomes is maintained.[1][2] Mitosis is preceded by the S phase of interphase (during which DNA replication occurs) and is followed by telophase and cytokinesis, which divide the cytoplasm, organelles, and cell membrane of one cell into two new cells containing roughly equal shares of these cellular components.[3] The different stages of mitosis altogether define the mitotic phase (M phase) of a cell cycle—the division of the mother cell into two daughter cells genetically identical to each other.[4]
The process of mitosis is divided into stages corresponding to the completion of one set of activities and the start of the next. These stages are preprophase (specific to plant cells), prophase, prometaphase, metaphase, anaphase, and telophase. During mitosis, the chromosomes, which have already duplicated during interphase, condense and attach to spindle fibers that pull one copy of each chromosome to opposite sides of the cell.[5] The result is two genetically identical daughter nuclei. The rest of the cell may then continue to divide by cytokinesis to produce two daughter cells.[6] The different phases of mitosis can be visualized in real time, using live cell imaging.[7]
An error in mitosis can result in the production of three or more daughter cells instead of the normal two. This is called tripolar mitosis and multipolar mitosis, respectively. These errors can be the cause of non-viable embryos that fail to implant.[8] Other errors during mitosis can induce mitotic catastrophe, apoptosis (programmed cell death) or cause mutations. Certain types of cancers can arise from such mutations.[9]
Mitosis occurs only in eukaryotic cells and varies between organisms.[10] For example, animal cells generally undergo an open mitosis, where the nuclear envelope breaks down before the chromosomes separate, whereas fungal cells generally undergo a closed mitosis, where chromosomes divide within an intact cell nucleus.[11][12] Most animal cells undergo a shape change, known as mitotic cell rounding, to adopt a near spherical morphology at the start of mitosis. Most human cells are produced by mitotic cell division. Important exceptions include the gametes – sperm and egg cells – which are produced by meiosis. Prokaryotes, bacteria and archaea which lack a true nucleus, divide by a different process called binary fission.[13] """
inputs = tokenizer(
[
alpaca_prompt.format(
"Generate Biology MCQs from this context", # instruction
input2, # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 200, use_cache = True)
result=tokenizer.batch_decode(outputs)
```
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
[More Information Needed]
### Generating More than One MCQs
```python
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer
model_id="DisgustingOzil/Academic-MCQ-Generator"
model = AutoPeftModelForCausalLM.from_pretrained(
model_id, # YOUR MODEL YOU USED FOR TRAINING
load_in_4bit = load_in_4bit,
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
input2="""Mitosis (/maɪˈtoʊsɪs/) is a part of the cell cycle in which replicated chromosomes are separated into two new nuclei. Cell division by mitosis is an equational division which gives rise to genetically identical cells in which the total number of chromosomes is maintained.[1][2] Mitosis is preceded by the S phase of interphase (during which DNA replication occurs) and is followed by telophase and cytokinesis, which divide the cytoplasm, organelles, and cell membrane of one cell into two new cells containing roughly equal shares of these cellular components.[3] The different stages of mitosis altogether define the mitotic phase (M phase) of a cell cycle—the division of the mother cell into two daughter cells genetically identical to each other.[4]
The process of mitosis is divided into stages corresponding to the completion of one set of activities and the start of the next. These stages are preprophase (specific to plant cells), prophase, prometaphase, metaphase, anaphase, and telophase. During mitosis, the chromosomes, which have already duplicated during interphase, condense and attach to spindle fibers that pull one copy of each chromosome to opposite sides of the cell.[5] The result is two genetically identical daughter nuclei. The rest of the cell may then continue to divide by cytokinesis to produce two daughter cells.[6] The different phases of mitosis can be visualized in real time, using live cell imaging.[7]
An error in mitosis can result in the production of three or more daughter cells instead of the normal two. This is called tripolar mitosis and multipolar mitosis, respectively. These errors can be the cause of non-viable embryos that fail to implant.[8] Other errors during mitosis can induce mitotic catastrophe, apoptosis (programmed cell death) or cause mutations. Certain types of cancers can arise from such mutations.[9]
Mitosis occurs only in eukaryotic cells and varies between organisms.[10] For example, animal cells generally undergo an open mitosis, where the nuclear envelope breaks down before the chromosomes separate, whereas fungal cells generally undergo a closed mitosis, where chromosomes divide within an intact cell nucleus.[11][12] Most animal cells undergo a shape change, known as mitotic cell rounding, to adopt a near spherical morphology at the start of mitosis. Most human cells are produced by mitotic cell division. Important exceptions include the gametes – sperm and egg cells – which are produced by meiosis. Prokaryotes, bacteria and archaea which lack a true nucleus, divide by a different process called binary fission.[13] """
def partition(total_text):
# Split the text into words
words = total_text.split()
total_words = len(words)
print(total_words)
# Determine the number of words per partition, aiming for 5 equal parts
words_per_partition = total_words // 5
partitions = []
# Create partitions
for i in range(0, total_words, words_per_partition):
partition = " ".join(words[i:i+words_per_partition])
if len(partition)>100:
partitions.append(partition)
return partitions
partitions=partition(input2)
import re
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
pattern = r'<question>(.*?)</question>.*?<answer>(.*?)</answer>'
mcq_pattern = r'<question>(.*?)</question>.*?<answer>(.*?)</answer>.*?<distractor>(.*?)</distractor>'
# for part in partitions:
for part in partitions:
inputs = tokenizer(
[
alpaca_prompt.format(
"Generate Biology MCQs from this context", # instruction
part, # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens = 200, use_cache = True)
result=tokenizer.batch_decode(outputs)
matches = re.findall(mcq_pattern, result[0], re.DOTALL)
question = matches[0][0].strip()
correct_answer = matches[0][1].strip()
distractors = [d.strip() for d in matches[0][2].split('<d>') if d.strip()]
print(question)
print(correct_answer)
print("Distractors:", distractors)
outputs = model.generate(**inputs, max_new_tokens = 200, use_cache = True,temperature=0.9,
top_k=50,
top_p=0.95,
no_repeat_ngram_size=2,)
result=tokenizer.batch_decode(outputs)
matches=None
matches = re.findall(mcq_pattern, result[0], re.DOTALL)
if len(matches)==0:
matches = re.findall(pattern, result[0], re.DOTALL)
print(matches)
question = matches[0][0].strip()
correct_answer = matches[0][1].strip()
print("Question:", question)
print("Correct Answer:", correct_answer)
else:
print(matches)
question = matches[0][0].strip()
correct_answer = matches[0][1].strip()
distractors = [d.strip() for d in matches[0][2].split('<d>') if d.strip()]
print("Question:", question)
print("Correct Answer:", correct_answer)
print("Distractors:", distractors)
```
### Gradio App for it
```python
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import re
model_id = "DisgustingOzil/Academic-MCQ-Generator"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
def partition_text(text, partition_size=9):
words = text.split()
total_words = len(words)
words_per_partition = total_words // partition_size
partitions = []
for i in range(0, total_words, words_per_partition):
partition = " ".join(words[i:i+words_per_partition])
if len(partition) > 100: # Ensuring meaningful length for MCQ generation
partitions.append(partition)
return partitions
def generate_mcqs_for_partition(Instruction,partition):
# Adjust with the actual model calling and response parsing logic
inputs = tokenizer(
[
alpaca_prompt.format(
Instruction, # instruction
partition, # input
"", # output - leave this blank for generation!
)
], return_tensors = "pt").to("cuda")
# print(partition)
outputs = model.generate(**inputs, max_length=512, num_return_sequences=1)
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# print()
return output_text
def generate_mcqs(Instruction,text):
partitions = partition_text(text)
mcqs_output = []
for part in partitions:
output_text = generate_mcqs_for_partition(Instruction,part)
pattern = r'<question>(.*?)</question>.*?<answer>(.*?)</answer>.*?<distractor>(.*?)</distractor>'
matches = re.findall(pattern, output_text, re.DOTALL)
for match in matches:
question = match[0].strip()
correct_answer = match[1].strip()
distractors = [d.replace('</d>', '').strip() for d in match[2].split('<d>') if d.strip()]
distractors_formatted = ',\n'.join(distractors)
mcqs_output.append(f"Question: {question}\nCorrect Answer: {correct_answer}\nDistractors: {distractors_formatted}\n")
return "\n".join(mcqs_output) if mcqs_output else "No MCQs could be generated from the input."
iface = gr.Interface(fn=generate_mcqs,
inputs=[gr.Textbox(label="Instruction"),gr.Textbox(lines=10, label="Input Biology Text")
],
outputs="text",
title="Biology MCQ Generator",
description="Enter a text about Biology to generate MCQs.")
if __name__ == "__main__":
iface.launch(debug=True,share=True)
```
|