Model Description
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
!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
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)
[More Information Needed]
Generating More than One MCQs
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
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)