Smart MCQ Solver
NLP-based MCQ answering system using Transformers, RAG, semantic retrieval, FAISS, and Cross-Encoder reranking, with leakage-aware validation and modular ML pipelines.
- PyTorch
- PyTorch Lightning
- RAG
- Transformers
- Hugging Face
- W&B

Overview
Smart MCQ Solver is an experimental Natural Language Processing (NLP) framework designed to solve multiple-choice questions using classical machine learning, deep learning, pretrained transformer architectures, and retrieval-augmented approaches.
Developed as part of the Deep Learning and Generative AI coursework at IIT Madras, the project explores different approaches to Multiple Choice Question Answering (MCQA), comparing their predictive performance, generalization capabilities, and computational requirements.
The system ranks the three most probable answers from five candidate options for each question, optimizing performance against the Mean Average Precision at 3 (MAP@3) evaluation metric.
Beyond model development, the project focuses on leakage-aware validation, semantic retrieval, experiment tracking, and modular training and inference pipelines.
Problem Statement
Multiple-choice question answering requires a model to understand natural language, interpret contextual relationships, evaluate competing answer choices, and rank them according to their relevance.
Traditional machine learning approaches can identify statistical patterns in text but have limited ability to capture contextual relationships. Deep learning and pretrained language models offer richer representations, although their effectiveness depends on data quality, training methodology, and available computational resources.
The objective of this project was to investigate these trade-offs by developing and evaluating multiple architectures on a common benchmark.
The primary objectives were to:
- Predict the three most probable answers from five candidate options.
- Compare classical machine learning, custom deep learning, and pretrained transformer architectures.
- Investigate whether retrieved contextual information improves question-answering performance.
- Develop a validation methodology that reduces data leakage.
- Build modular pipelines for training, inference, and experimentation.
My Contribution
I designed and implemented the machine learning workflow, from exploratory data analysis and preprocessing to model development, training, evaluation, and deployment of an interactive demonstration.
My key contributions include:
- Conducted exploratory data analysis to identify duplicate questions, semantic similarities, answer-position biases, and potential data leakage.
- Developed a semantic grouping strategy using Sentence Transformers, cosine similarity, and StratifiedGroupKFold to improve validation integrity.
- Implemented a TF-IDF and LightGBM baseline to establish a computationally efficient performance benchmark.
- Designed a custom attention-based Bidirectional LSTM architecture with trainable word embeddings and a custom tokenizer.
- Fine-tuned BERT, RoBERTa, and DeBERTa-v3 using a shared multiple-choice classification architecture.
- Evaluated zero-shot classification using BART to investigate pretrained model performance without task-specific fine-tuning.
- Developed a retrieval-augmented question-answering pipeline using FAISS vector search and cross-encoder reranking.
- Implemented modular training and inference pipelines using PyTorch Lightning, including checkpointing, early stopping, and experiment tracking.
- Developed inference workflows for individual models and transformer ensembles.
- Documented the experimental methodology, architecture, results, and limitations in a technical report.
System Architecture
The system follows a modular machine learning architecture that separates data preparation, model development, contextual retrieval, training, evaluation, and inference.
| Component | Responsibility |
|---|---|
| Data Pipeline | Exploratory analysis, text cleaning, deduplication, semantic grouping, and dataset splitting |
| Feature Engineering | TF-IDF vectors, custom word tokenization, and transformer-specific tokenization |
| Model Layer | Classical ML, BiLSTM, pretrained transformers, and zero-shot models |
| Retrieval Layer | Sentence embeddings, FAISS indexing, semantic search, and cross-encoder reranking |
| Training Pipeline | Optimization, validation, checkpointing, and experiment tracking |
| Inference Pipeline | Candidate scoring, answer ranking, ensemble inference, and prediction generation |
| Demonstration | Interactive question-answering interface hosted on Hugging Face Spaces |
Dataset and Preprocessing
The dataset consists of question prompts, five candidate answer choices, and the corresponding correct answer labels.
Each question is transformed into five question-option pairs, allowing models to independently evaluate the relationship between the question and each candidate answer.
The preprocessing pipeline includes text normalization, duplicate detection, semantic grouping, and stratified dataset splitting.
Two versions of the processed dataset were developed as the experimental methodology evolved. The second version introduced stronger safeguards against leakage caused by duplicate and semantically equivalent questions.
Classical Machine Learning Baseline
A TF-IDF and LightGBM pipeline was implemented to establish a lightweight performance baseline.
The TF-IDF vectorizer converts question-option pairs into sparse numerical feature vectors using unigram and bigram representations. These features are passed to a gradient-boosted decision tree classifier to estimate candidate answer relevance.
This baseline provides a reference for determining whether more computationally expensive architectures deliver meaningful improvements.
Custom Attention-Based BiLSTM
A custom Bidirectional Long Short-Term Memory network was developed to investigate learning contextual text representations directly from the training dataset.
The architecture consists of:
- A custom vocabulary and word tokenizer.
- Trainable 128-dimensional word embeddings.
- Two stacked bidirectional LSTM layers.
- Attention-based pooling with padding masks.
- Fully connected classification layers with ReLU activation and dropout.
The attention mechanism learns to assign different importance weights to sequence tokens, producing a contextual representation for each question-option pair.
The resulting relevance scores are grouped into five candidate scores, from which the three highest-ranked answers are selected.
Transformer-Based Architecture
Three pretrained transformer architectures were fine-tuned using a shared classification pipeline:
| Model | Architecture | Tokenization |
|---|---|---|
| BERT | Bidirectional transformer encoder | WordPiece |
| RoBERTa | Optimized BERT-style encoder | Byte-Pair Encoding |
| DeBERTa-v3 | Transformer with disentangled attention | SentencePiece |
Each question-option pair is processed using the corresponding pretrained tokenizer and transformer encoder.
The first-token representation from the encoder is passed through a custom classification head consisting of fully connected layers, GeLU activation, and dropout regularization.
The classification head produces an individual relevance score for each candidate answer. These scores are combined to generate the final ranked predictions.
A common training pipeline allows the transformer architectures to be evaluated under broadly comparable conditions.
Retrieval-Augmented Question Answering
To investigate whether additional contextual information improves predictions, I developed a two-stage retrieval pipeline.
Stage 1 — Knowledge Base Construction
Question prompts and their correct answers are combined into documents using the training corpus. These documents are encoded into dense vector representations using the all-MiniLM-L6-v2 Sentence Transformer and indexed using FAISS.
Stage 2 — Retrieval and Context Augmentation
For each input question:
- Generate a semantic embedding using the same Sentence Transformer.
- Retrieve the 20 most similar documents from the FAISS index.
- Rerank the retrieved documents using the ms-marco-MiniLM-L-6-v2 cross-encoder.
- Select the five highest-ranked documents.
- Combine the retrieved context with the original question.
- Pass the augmented input to the transformer classifier.
- Rank the five candidate answers and return the top three.
The retrieval pipeline investigates how contextual knowledge can complement the pretrained representations of transformer models.
Although described as RAG within the project, the final prediction mechanism performs answer classification and ranking rather than free-form text generation.
Training and Experimentation Pipeline
PyTorch Lightning was used to organize the training and validation workflows across the deep learning architectures.
The training strategy includes:
- AdamW optimization.
- Cross-entropy loss.
- Gradient clipping with a threshold of 1.0.
- Early stopping based on validation MAP@3, with a patience of five epochs.
- Checkpoint selection based on the best validation MAP@3 score.
- Model-specific optimizer configuration.
- Multi-GPU training using Distributed Data Parallel.
- Experiment tracking and metric visualization using Weights & Biases.
The modular implementation separates model definitions, training scripts, inference scripts, and experimental notebooks, supporting systematic experimentation across different configurations.
Engineering Challenges
Identifying and Mitigating Data Leakage
One of the most significant challenges was identifying leakage between the training and validation datasets.
Exploratory data analysis revealed 183 duplicate samples after ignoring answer-option ordering, along with numerous repeated and semantically similar question prompts.
Initial experiments produced optimistic validation results that did not translate into comparable leaderboard performance.
Grouping questions solely by their exact prompt text was insufficient because differently worded questions could still express the same underlying meaning.
To address this issue, I introduced a revised preprocessing pipeline that:
- Detects duplicates independently of answer-option ordering.
- Generates semantic embeddings for question prompts.
- Groups semantically similar questions using cosine similarity.
- Applies StratifiedGroupKFold to keep grouped questions within the same dataset partition.
This approach improved the integrity of the validation methodology and reduced the risk of evaluating models on near-duplicate training examples.
Distributed Training and Unused Parameters
While fine-tuning transformer models across two GPUs using Distributed Data Parallel, I encountered issues caused by unused pretrained pooler parameters.
The custom classification head operates directly on the first-token representation rather than the pretrained pooler output. Consequently, the unused pooler parameters did not receive gradients during backpropagation.
Freezing the unused pooler layer resolved the associated distributed training issue without removing the transformer encoder from task-specific fine-tuning.
This provided practical insight into gradient flow, trainable parameter management, and distributed model execution.
Retrieval Quality and Computational Overhead
Semantic similarity alone does not necessarily guarantee that retrieved documents contain useful evidence for answering a question.
To improve contextual relevance, the retrieval pipeline combines efficient vector search with cross-encoder reranking.
However, retrieval augmentation introduces additional preprocessing and computation, while the longer model inputs increase training overhead.
The experiments demonstrated that adding contextual retrieval does not automatically produce substantial predictive improvements. Its effectiveness depends on the quality of the knowledge base, retrieval relevance, and the model's ability to use the retrieved information.
Model Complexity versus Predictive Performance
Larger pretrained models generally outperformed the custom BiLSTM architecture. However, the classical LightGBM baseline remained highly competitive on the public leaderboard.
This highlighted the importance of evaluating architecture choices against actual experimental results rather than assuming that increasing model complexity guarantees better performance.
Technical Decisions
| Decision | Rationale |
|---|---|
| Question-option pair representation | Allows independent contextual evaluation of each candidate answer |
| TF-IDF and LightGBM baseline | Establishes an efficient benchmark for evaluating more complex architectures |
| Custom attention-based BiLSTM | Investigates task-specific representation learning without pretrained transformer weights |
| Pretrained transformer fine-tuning | Leverages language representations learned from large-scale pretraining |
| Sentence Transformers | Generates semantic embeddings for duplicate grouping and contextual retrieval |
| FAISS | Enables efficient similarity search over dense vector representations |
| Cross-encoder reranking | Refines retrieved documents through joint question-document relevance scoring |
| StratifiedGroupKFold | Reduces cross-partition leakage while approximately preserving class distributions |
| PyTorch Lightning | Standardizes training, validation, checkpointing, and distributed execution |
| Weights & Biases | Supports experiment tracking and comparative performance analysis |
| MAP@3-based checkpointing | Aligns model selection with the competition's ranking-based evaluation metric |
Results & Outcomes
The project evaluated nine experimental configurations across classical machine learning, custom deep learning, zero-shot classification, pretrained transformers, and retrieval-augmented transformers.
Evaluation Metrics
Model performance was evaluated using:
- Top-1 Accuracy: Whether the correct answer is ranked first.
- Top-3 Accuracy: Whether the correct answer appears among the three highest-ranked predictions.
- MAP@3: Measures prediction correctness while rewarding higher positions in the ranked answer list.
- Validation Loss: Tracks classification performance during optimization.
- Training Duration: Measures the computational cost of different architectures.
Comparative Model Performance
The following results were obtained from experiments using the revised, leakage-aware preprocessing methodology.
| Model | Validation MAP@3 | Public Kaggle MAP@3 |
|---|---|---|
| DeBERTa-v3 + Retrieval | 0.8567 | 0.7502 |
| BERT + Retrieval | 0.8529 | 0.7444 |
| DeBERTa-v3 | 0.8514 | 0.7485 |
| RoBERTa | 0.8433 | 0.7294 |
| RoBERTa + Retrieval | 0.8205 | 0.7465 |
| BERT | 0.8105 | 0.7394 |
| Custom BiLSTM | 0.7023 | 0.6995 |
| TF-IDF + LightGBM | — | 0.7502 |
| Zero-Shot BART | — | 0.4996 |
Key Experimental Findings
Pretrained models outperform training from scratch. Fine-tuned transformer architectures demonstrated stronger validation and leaderboard performance than the custom BiLSTM model.
Classical machine learning remains competitive. The TF-IDF and LightGBM baseline achieved a public MAP@3 score of 0.7502, matching the best retrieval-augmented configuration in the revised experiments.
Retrieval augmentation provides limited improvements. DeBERTa-v3 achieved a validation MAP@3 of 0.8514 without retrieval and 0.8567 with retrieval. However, its training time per epoch increased from approximately 85 seconds to 300 seconds.
Validation methodology matters. Earlier experiments achieved a maximum public leaderboard MAP@3 of 0.75311 and a public leaderboard rank of 610 using RoBERTa with retrieval augmentation. These experiments were conducted before the validation leakage issue was addressed and are therefore reported separately from the revised experimental results.
Model complexity does not guarantee superior results. The experiments demonstrated that data quality, validation integrity, feature representation, and contextual relevance are as important as architecture selection.
The completed project includes a modular experimentation framework, trained-model inference pipelines, automated Kaggle submission generation, an interactive demonstration, and a detailed technical report.
Lessons Learned
Developing Smart MCQ Solver strengthened my understanding of both machine learning engineering and experimental methodology.
The project provided practical experience in:
- Designing custom neural network architectures using PyTorch.
- Fine-tuning pretrained language models for downstream NLP tasks.
- Understanding tokenization, embeddings, attention mechanisms, and contextual representations.
- Developing semantic retrieval pipelines using vector embeddings and similarity search.
- Applying cross-encoder reranking to improve contextual relevance.
- Identifying data leakage and designing more reliable validation strategies.
- Debugging gradient flow and distributed training issues.
- Comparing model performance against computational requirements.
- Structuring reusable training and inference pipelines.
- Tracking experiments and interpreting evaluation metrics.
The most important learning was that successful machine learning systems depend not only on sophisticated architectures but also on rigorous evaluation, reliable data pipelines, and evidence-driven engineering decisions.
Future Improvements
Potential directions for further development include:
- Expanding the retrieval knowledge base using external, domain-relevant information sources.
- Ensuring retrieval indexes are constructed exclusively from the corresponding training partition during validation.
- Investigating hybrid lexical and semantic retrieval strategies.
- Performing systematic retrieval ablation studies.
- Evaluating alternative attention pooling and classification architectures.
- Optimizing inference latency through model quantization and batching.
- Evaluating model ensembles under consistent validation conditions.
- Introducing confidence calibration and uncertainty estimation.
- Improving generalization to questions from previously unseen domains.