Update README.md
Browse files7 unmodified lines89101112131415161718192021222324259 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306317 unmodified lines- unsloth/Qwen2.5-Coder-1.5B-Instructpipeline_tag: text-generation---# Using tuandunghcmut/Qwen25_Coder_MultipleChoiceThe project "Knowledge Distillation About YAML-Based Structured Multi-Step Reasoning from a Teacher Model GPT-4o to a Small LLM: Qwen2.5 Coder 1.5B-Instruct" focuses on distilling structured multi-step reasoning from GPT-4o into a smaller model.This document provides everything you need to get started with tuandunghcmut/Qwen25_Coder_MultipleChoice, a model designed for multiple-choice coding questions.I plan to refactor the project into a well-structured GitHub repository, expand the dataset, and re-train it later with distributed training for better scalability.## Installation and Setup### PrerequisitesMake sure you have Python 3.8+ installed. Then install the required packages:```bash# Install core dependencies9 unmodified linespip install datasets pyyaml```### Flash Attention SetupFlash Attention provides a significant speedup for transformer models. To use it with the Qwen model:1. Install Flash Attention as shown above2. Enable it when loading the model:```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer# Enable Flash Attention during model loadingmodel = AutoModelForCausalLM.from_pretrained("tuandunghcmut/Qwen25_Coder_MultipleChoice",torch_dtype=torch.bfloat16,device_map="auto",trust_remote_code=True,use_flash_attention_2=True # Enable Flash Attention)```Flash Attention will provide:- 2-3x faster inference speed- Lower memory usage- Compatible with 4-bit quantization for even more efficiency### Environment VariablesIf you're using Hugging Face Hub models, you may want to set up your access token:```bash# Set environment variable for Hugging Face tokenexport HF_TOKEN="your_huggingface_token_here"# Or in Pythonimport osos.environ["HF_TOKEN"] = "your_huggingface_token_here"```### GPU SetupFor optimal performance, you'll need a CUDA-compatible GPU. Check your installation:```bash# Verify CUDA is availablepython -c "import torch; print('CUDA available:', torch.cuda.is_available())"# Print CUDA device infopython -c "import torch; print('CUDA device count:', torch.cuda.device_count()); print('CUDA device name:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'No GPU')"```## Required ClassesBelow are the essential classes needed to work with the model. Copy these into your Python files to use them in your project.### PromptCreatorThis class formats prompts for multiple-choice questions:```pythonclass PromptCreator:"""Creates and formats prompts for multiple choice questionsSupports different prompt styles for training and inference"""# Prompt typesBASIC = "basic" # Simple answer-only formatYAML_REASONING = "yaml" # YAML formatted reasoningTEACHER_REASONED = "teacher" # Same YAML format as YAML_REASONING but using teacher completions for trainingdef __init__(self, prompt_type=BASIC):self.prompt_type = prompt_type# Initialize parser mode based on prompt typeif prompt_type == self.YAML_REASONING or prompt_type == self.TEACHER_REASONED:self.parser_mode = "yaml"else:self.parser_mode = "basic"def format_choices(self, choices):"""Format choices with letter prefixes"""return "\n".join([f"{chr(65 + i)}. {choice}" for i, choice in enumerate(choices)])def get_max_letter(self, choices):"""Get the last valid letter based on choice count"""return chr(65 + len(choices) - 1)def create_inference_prompt(self, question, choices):"""Create a prompt for inference based on the configured prompt type"""formatted_choices = self.format_choices(choices)max_letter = self.get_max_letter(choices)if self.prompt_type == self.BASIC:return self._create_basic_prompt(question, formatted_choices, max_letter)elif self.prompt_type == self.YAML_REASONING or self.prompt_type == self.TEACHER_REASONED:return self._create_yaml_prompt(question, formatted_choices, max_letter)else:return self._create_basic_prompt(question, formatted_choices, max_letter)def _create_basic_prompt(self, question, formatted_choices, max_letter):"""Create a basic prompt that just asks for an answer letter"""return f"""{question}{formatted_choices}Select the correct answer from A through {max_letter}:"""def _create_yaml_prompt(self, question, formatted_choices, max_letter):"""Create a prompt with YAML formatted reasoning structure"""return f"""{question}{formatted_choices}Think through this step-by-step:- Understand what the question is asking- Analyze each option carefully- Reason about why each option might be correct or incorrect- Select the most appropriate answerYour response should be in YAML format:understanding: |<your understanding of the question>analysis: |<your analysis of each option>reasoning: |<your reasoning about the correct answer>conclusion: |<your final conclusion>answer: <single letter A through {max_letter} representing your final answer>"""def create_training_prompt(self, question, choices):"""Create a prompt for training based on the configured prompt type"""formatted_choices = self.format_choices(choices)max_letter = self.get_max_letter(choices)if self.prompt_type == self.BASIC:return self._create_basic_training_prompt(question, formatted_choices, max_letter)elif self.prompt_type == self.YAML_REASONING or self.prompt_type == self.TEACHER_REASONED:return self._create_yaml_training_prompt(question, formatted_choices, max_letter)else:return self._create_basic_training_prompt(question, formatted_choices, max_letter)def _create_basic_training_prompt(self, question, formatted_choices, max_letter):"""Create a basic training prompt"""return f"""{question}{formatted_choices}Select the correct answer from A through {max_letter}:"""def _create_yaml_training_prompt(self, question, formatted_choices, max_letter):"""Create a training prompt with YAML formatted reasoning structure"""return f"""{question}{formatted_choices}Think through this step-by-step:- Understand what the question is asking- Analyze each option carefully- Reason about why each option might be correct or incorrect- Select the most appropriate answerYour response should be in YAML format:understanding: |<your understanding of the question>analysis: |2 unmodified lines<your reasoning about the correct answer>conclusion: |<your final conclusion>answer: <single letter A through {max_letter} representing your final answer>"""def set_prompt_type(self, prompt_type):"""Set the prompt type and update parser mode accordingly"""self.prompt_type = prompt_typeif prompt_type == self.YAML_REASONING or prompt_type == self.TEACHER_REASONED:self.parser_mode = "yaml"else:self.parser_mode = "basic"def is_teacher_mode(self):"""Check if prompt type is teacher mode"""return self.prompt_type == self.TEACHER_REASONED```### ResponseParserThis class extracts answers from model responses:```pythonclass ResponseParser:"""Parser for model responses with support for different formatsExtracts answers and reasoning from model outputs"""# Parser modesBASIC = "basic" # Extract single letter answerYAML = "yaml" # Parse YAML formatted response with reasoningdef __init__(self, parser_mode=BASIC):"""Initialize with parser mode (basic or yaml)"""self.parser_mode = parser_modedef parse(self, response_text):"""Parse the response text and extract answer and reasoning"""if self.parser_mode == self.YAML:return self._parse_yaml_response(response_text)else:return self._parse_basic_response(response_text)def _parse_basic_response(self, response_text):"""Parse a basic response to extract the answer letterReturns:tuple: (answer_letter, None)"""# Look for just the letter at the end of textimport re# Try to find the last occurrence of letters A-Z by themselvesmatches = re.findall(r'\b([A-Z])\b', response_text)if matches:return matches[-1], None # Return the last matching letter# Try to find "The answer is X" patternanswer_match = re.search(r'[Tt]he answer is[:\s]+([A-Z])', response_text)if answer_match:return answer_match.group(1), None# If nothing else works, just get the last uppercase letteruppercase_letters = re.findall(r'[A-Z]', response_text)if uppercase_letters:return uppercase_letters[-1], Nonereturn None, None # No answer founddef _parse_yaml_response(self, response_text):"""Parse a YAML formatted response to extract the answer and reasoningReturns:tuple: (answer_letter, reasoning_dict)"""import reimport yaml# First try to extract just the answer fieldanswer_match = re.search(r'answer:\s*([A-Z])', response_text)answer = answer_match.group(1) if answer_match else None# Try to extract the entire YAMLtry:# Remove potential code block markersyaml_text = response_textif "```yaml" in yaml_text:yaml_text = yaml_text.split("```yaml")[1]if "```" in yaml_text:yaml_text = yaml_text.split("```")[0]elif "```" in yaml_text:# Assume the whole thing is a code blockparts = yaml_text.split("```")if len(parts) >= 3:yaml_text = parts[1]# Parse the YAMLparsed_yaml = yaml.safe_load(yaml_text)# If successful, use the answer from the YAML, and return the parsed structureif isinstance(parsed_yaml, dict) and "answer" in parsed_yaml:return parsed_yaml.get("answer"), parsed_yamlexcept Exception:# If YAML parsing fails, we already have the answer from regexpassreturn answer, Nonedef set_parser_mode(self, parser_mode):"""Set the parser mode"""self.parser_mode = parser_mode@classmethoddef from_prompt_type(cls, prompt_type):"""Create a ResponseParser with the appropriate mode based on prompt typeArgs:prompt_type: The prompt type (e.g., PromptCreator.YAML_REASONING)Returns:ResponseParser: A parser configured for the prompt type"""if prompt_type in ["yaml", "teacher"]:return cls("yaml")else:return cls("basic")```### QwenModelHandlerThis class handles model loading and inference:```pythonclass QwenModelHandler:def __init__(self, model_name="unsloth/Qwen2.5-7B", max_seq_length=768,quantization=None, device_map="auto", cache_dir=None,use_flash_attention=True):"""Initialize a handler for Qwen modelsArgs:model_name: Model identifier (local path or Hugging Face model ID)max_seq_length: Maximum sequence lengthquantization: Quantization method ("4bit", "8bit", or None)device_map: Device mapping strategycache_dir: Directory to cache downloaded modelsuse_flash_attention: Whether to use Flash Attention 2 for faster inference"""self.model_name = model_nameself.max_seq_length = max_seq_lengthself.quantization = quantizationself.device_map = device_mapself.cache_dir = cache_dirself.use_flash_attention = use_flash_attentionself.model = Noneself.tokenizer = None# Load the model and tokenizerself._load_model()def _load_model(self):"""Load the model and tokenizer with appropriate settings"""from transformers import AutoModelForCausalLM, AutoTokenizerimport torch# Load tokenizerself.tokenizer = AutoTokenizer.from_pretrained(self.model_name,trust_remote_code=True,cache_dir=self.cache_dir)# Prepare model loading kwargsmodel_kwargs = {"trust_remote_code": True,"cache_dir": self.cache_dir,"device_map": self.device_map,}# Add Flash Attention if requested and availableif self.use_flash_attention:try:import flash_attnmodel_kwargs["use_flash_attention_2"] = Trueprint("Flash Attention 2 enabled!")except ImportError:print("Flash Attention not available. For faster inference, install with: pip install flash-attn")# Add quantization if specifiedif self.quantization == "4bit":try:from transformers import BitsAndBytesConfigmodel_kwargs["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_compute_dtype=torch.bfloat16)except ImportError:print("bitsandbytes not available, loading without 4-bit quantization")elif self.quantization == "8bit":model_kwargs["load_in_8bit"] = Trueelse:model_kwargs["torch_dtype"] = torch.bfloat16# Load the modelself.model = AutoModelForCausalLM.from_pretrained(self.model_name,**model_kwargs)def generate_with_streaming(self, prompt, temperature=0.7, max_tokens=1024, stream=True):"""Generate text from the model with optional streamingArgs:prompt: Input text prompttemperature: Temperature for sampling (0 for deterministic)max_tokens: Maximum number of tokens to generatestream: Whether to stream the outputReturns:String containing the generated text, or generator if streaming"""import torch# Tokenize promptinputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)input_ids = inputs.input_idsattention_mask = inputs.attention_mask# Set generation parametersgeneration_config = {"max_new_tokens": max_tokens,"temperature": temperature,"do_sample": temperature > 0,"top_p": 0.95 if temperature > 0 else 1.0,"repetition_penalty": 1.1,"pad_token_id": self.tokenizer.eos_token_id,}# If not streaming, do normal generationif not stream:with torch.no_grad():outputs = self.model.generate(input_ids=input_ids,attention_mask=attention_mask,**generation_config)# Decode the generated text (skip the prompt)generated_text = self.tokenizer.decode(outputs[0][input_ids.shape[1]:],skip_special_tokens=True)return generated_text# If streaming, yield generated tokens one by oneelse:generated = []# Initialize generatorwith torch.no_grad():generated_ids = self.model.generate(input_ids=input_ids,attention_mask=attention_mask,**generation_config,streamer=None # Would need a custom streamer here if available)# Decode the entire sequence at once (not truly streaming, but simpler)full_text = self.tokenizer.decode(generated_ids[0][input_ids.shape[1]:],skip_special_tokens=True)return full_text```## Hardware Requirements and Optimization### Flash Attention BenefitsFlash Attention is a highly optimized implementation of the attention mechanism that:1. **Speeds up inference by 2-3x** compared to standard attention2. **Reduces memory usage** by avoiding materializing large attention matrices3. **Works perfectly with 4-bit quantization** for even further optimization4. **Scales better with sequence length**, which is important for complex coding questionsFor the best performance, make sure to:- Install Flash Attention (`pip install flash-attn`)- Enable it when loading the model (see QwenModelHandler class)- Use with CUDA-compatible NVIDIA GPUs### Hardware RecommendationsFor optimal performance, we recommend:- **GPU**: NVIDIA GPU with at least 8GB VRAM (16GB+ recommended for larger models)- **RAM**: 16GB+ system RAM- **Storage**: At least 10GB free disk space for model files- **CPU**: Modern multi-core processor (for preprocessing)### Reducing Memory UsageIf you're facing memory constraints:```python# Use 4-bit quantization with Flash Attention for optimal memory-efficiencymodel_handler = QwenModelHandler(model_name="tuandunghcmut/Qwen25_Coder_MultipleChoice",quantization="4bit",use_flash_attention=True)# Further optimize with unslothtry:from unsloth.models import FastLanguageModelFastLanguageModel.for_inference(model_handler.model)print("Using unsloth for additional optimization")except ImportError:print("unsloth not available")```## Usage ExampleHere's how to use these classes with Flash Attention enabled:```python# 1. Load the model with Flash Attention and 4-bit quantizationfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torchhub_model_id = "tuandunghcmut/Qwen25_Coder_MultipleChoice"# Create model handler with Flash Attention and 4-bit quantizationmodel_handler = QwenModelHandler(model_name=hub_model_id,max_seq_length=2048,quantization="4bit",use_flash_attention=True)# Optional: Use unsloth for even faster inferencetry:from unsloth.models import FastLanguageModelFastLanguageModel.for_inference(model_handler.model)print("Using unsloth for faster inference")except ImportError:print("unsloth not available, using standard inference")# 2. Create prompt creator with YAML reasoning formatprompt_creator = PromptCreator(PromptCreator.YAML_REASONING)# 3. Example questionquestion = "Which of the following correctly defines a list comprehension in Python?"choices = ["[x**2 for x in range(10)]","for(x in range(10)) { return x**2; }","map(lambda x: x**2, range(10))","[for x in range(10): x**2]"]# 4. Create prompt and generate answerprompt = prompt_creator.create_inference_prompt(question, choices)response = model_handler.generate_with_streaming(prompt, temperature=0.0, stream=False)# 5. Parse the responseparser = ResponseParser(prompt_creator.parser_mode)answer, reasoning = parser.parse(response)print(f"Question: {question}")print(f"Answer: {answer}")if reasoning:print(f"Reasoning: {reasoning}")```## Troubleshooting### Common Issues1. **Flash Attention Installation Issues**: If you encounter problems installing `flash-attn`:```bash# Try with specific CUDA version (e.g., for CUDA 11.8)pip install flash-attn==2.3.4+cu118 --no-build-isolation# For older GPUspip install flash-attn==2.3.4 --no-build-isolation```2. **CUDA Out of Memory**: Try combining 4-bit quantization with Flash Attention.```pythonmodel_handler = QwenModelHandler(model_name=hub_model_id,quantization="4bit",use_flash_attention=True)```3. **Module Not Found Errors**: Make sure you've installed all required packages.```bashpip install transformers torch unsloth datasets pyyaml bitsandbytes flash-attn```4. **Parsing Errors**: If the model isn't producing valid YAML responses, try adjusting the temperature:```pythonresponse = model_handler.generate_with_streaming(prompt, temperature=0.0, stream=False)```### Getting HelpIf you encounter issues, check the [model repository on Hugging Face](https://huggingface.co/tuandunghcmut/Qwen25_Coder_MultipleChoice) for updates and community discussions.This guide provides you with all the necessary code and optimization techniques to use the model effectively for multiple-choice coding questions.7 unmodified lines89101112131415161718192021222324252627282930319 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204212 unmodified lines42442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512467 unmodified lines- unsloth/Qwen2.5-Coder-1.5B-Instructpipeline_tag: text-generation---# Qwen25_Coder_MultipleChoice* This project focuses on distilling YAML-based structured multi-step reasoning capabilities from the GPT-4o teacher model into the smaller Qwen2.5 Coder 1.5B-Instruct LLM.* This document provides guidance on getting started with `tuandunghcmut/Qwen25_Coder_MultipleChoice`, a model fine-tuned for multiple-choice coding questions.* Future plans include refactoring the project into a well-structured GitHub repository, expanding the dataset, and retraining the model using distributed training for improved scalability.* A demonstration notebook is available on Google Colab (click the badge below). Please note that the training code has been omitted from this notebook. It is intended solely for testing and inference using the latest checkpoint.[](https://drive.google.com/file/d/1Q4jtRjIkFWIAM82pAg4OBPCLjpQ8ndpI/view?usp=sharing)* Note: The Qwen2.5 Coder 1.5B-Instruct model might be too small for this task, and the current training dataset may be insufficient. Future iterations will explore using a larger model and more extensive data. However, the current model successfully adheres to the desired YAML format and demonstrates structured reasoning.* The guide below provides an explanation of the code presented in the notebook.## InstallationFirst, install the required dependencies:```bash# Install core dependencies9 unmodified linespip install datasets pyyaml```## Key ClassesThe project provides several key classes for working with the model:### 1. QwenModelHandler```pythonclass QwenModelHandler:"""Handler for Qwen models with inference and saving capabilities using Unsloth"""def __init__(self, model_name="unsloth/Qwen2.5-7B", max_seq_length=768,quantization=None, device_map="auto", cache_dir=None):"""Initialize model and tokenizer using UnslothArgs:model_name: Name or path of the model (preferably an unsloth model)max_seq_length: Maximum sequence length for the modelquantization: Quantization type (None, '4bit', '8bit') - for compatibilitydevice_map: Device mapping strategycache_dir: Cache directory for models"""```This class handles the core model operations:- Model loading and initialization- Text generation with streaming support- Perplexity calculation- Model saving and pushing to HuggingFace Hub### 2. PromptCreator```pythonclass PromptCreator:"""Creates and formats prompts for multiple choice questions"""# Prompt typesBASIC = "basic" # Simple answer-only formatYAML_REASONING = "yaml" # YAML formatted reasoningTEACHER_REASONED = "teacher" # Same YAML format but using teacher completions```This class manages prompt creation with three modes:- Basic: Simple answer-only format- YAML Reasoning: Structured reasoning in YAML format- Teacher Reasoned: YAML format with teacher completions for training### 3. ResponseParser```pythonclass ResponseParser:"""Parser for model responses with support for different formats"""# Parser modesBASIC = "basic" # Extract single letter answerYAML = "yaml" # Parse YAML formatted response with reasoning```This class handles response parsing:- Extracts answers from model responses- Parses YAML-formatted reasoning- Supports both basic and YAML formats### 4. MultipleChoiceTester```pythonclass MultipleChoiceTester:"""Framework for testing Qwen models on multiple choice questions"""def __init__(self, model_handler, prompt_creator=None):"""Initialize with model handler and prompt configurationArgs:model_handler: The QwenModelHandler instanceprompt_creator: Optional PromptCreator instance"""```This class provides a complete testing framework:- Single example inference- Batch processing- Dataset evaluation- Performance metrics tracking- Results saving and visualization## Full Class Implementations<details><summary>Click to expand/collapse full class implementations</summary>### 1. QwenModelHandler```pythonclass QwenModelHandler:"""Handler for Qwen models with inference and saving capabilities using Unsloth"""def __init__(self, model_name="unsloth/Qwen2.5-7B", max_seq_length=768,quantization=None, device_map="auto", cache_dir=None):self.model_name = model_nameself.max_seq_length = max_seq_lengthself.device_map = device_mapself.quantization = quantizationself.cache_dir = cache_dir# Convert quantization parameter to load_in_4bit parameter for Unslothself.load_in_4bit = quantization == "4bit"# Load tokenizer and modelself.tokenizer, self.model = self._load_model()self.response_parser = ResponseParser()def _load_model(self):"""Load model and tokenizer with Unsloth for optimization"""from unsloth import FastLanguageModelimport torchprint(f"Loading {self.model_name} with Unsloth, max_seq_length={self.max_seq_length}")# Set dtype based on hardwaredtype = None # None for auto detection# Load model and tokenizer with Unslothmodel, tokenizer = FastLanguageModel.from_pretrained(model_name=self.model_name,max_seq_length=self.max_seq_length,dtype=dtype,load_in_4bit=self.load_in_4bit,cache_dir=self.cache_dir,)return tokenizer, modeldef generate_with_streaming(self, prompt, temperature=0.7, max_tokens=1024, stream=True):"""Generate completion with optional streaming using Unsloth's optimized inference"""# Enable faster inferencefrom unsloth import FastLanguageModelFastLanguageModel.for_inference(self.model)# Format as chatmessages = [{"role": "user", "content": prompt}]chat_text = self.tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)# Tokenize inputmodel_inputs = self.tokenizer([chat_text], return_tensors="pt").to(self.model.device)# Generate with streaming if requestedif stream:from transformers import TextIteratorStreamerimport threading# Set up streamerstreamer = TextIteratorStreamer(self.tokenizer,skip_prompt=True,skip_special_tokens=True)# Start generation in a threadgeneration_kwargs = {"input_ids": model_inputs.input_ids,"attention_mask": model_inputs.attention_mask,"temperature": temperature,"max_new_tokens": max_tokens,"streamer": streamer,"do_sample": temperature > 0.0,"use_cache": True,"min_p": 0.1 if temperature > 0.0 else None,}thread = threading.Thread(target=self.model.generate, kwargs=generation_kwargs)thread.start()return streamerelse:# Generate without streaminggenerated_ids = self.model.generate(input_ids=model_inputs.input_ids,attention_mask=model_inputs.attention_mask,temperature=temperature,max_new_tokens=max_tokens,do_sample=temperature > 0.0,use_cache=True,min_p=0.1 if temperature > 0.0 else None,)# Decode the generated textgenerated_text = self.tokenizer.decode(generated_ids[0][model_inputs.input_ids.shape[1]:],skip_special_tokens=True)return generated_textdef calculate_perplexity(self, prompt, answer, temperature=0.0):"""Calculate perplexity for a prompt and answer pair"""import torch# Format chat for perplexity calculationmessages = [{"role": "user", "content": prompt},{"role": "assistant", "content": answer}]chat_text = self.tokenizer.apply_chat_template(messages,tokenize=False)# Tokenize the textencodings = self.tokenizer(chat_text, return_tensors="pt").to(self.model.device)# Calculate losswith torch.no_grad():outputs = self.model(**encodings, labels=encodings.input_ids)# Get loss and calculate perplexityneg_log_likelihood = outputs.loss.item()perplexity = torch.exp(torch.tensor(neg_log_likelihood)).item()return perplexitydef save_model(self, output_dir, save_method="lora"):"""Save model to disk using Unsloth's optimized methods"""import osos.makedirs(output_dir, exist_ok=True)# Use Unsloth's saving methodsif save_method == "lora":self.model.save_pretrained(output_dir)self.tokenizer.save_pretrained(output_dir)elif save_method == "merged_16bit":self.model.save_pretrained_merged(output_dir, self.tokenizer, save_method="merged_16bit")elif save_method == "merged_4bit":self.model.save_pretrained_merged(output_dir, self.tokenizer, save_method="merged_4bit")elif save_method == "gguf":self.model.save_pretrained_gguf(output_dir, self.tokenizer, quantization_method="q4_k_m")else:raise ValueError(f"Unknown save method: {save_method}")print(f"Model saved to {output_dir} using method {save_method}")return output_dirdef push_to_hub(self, repo_id, token=None, save_method="lora", private=False):"""Push model to Hugging Face Hub using Unsloth's optimized methods"""if save_method == "lora":self.model.push_to_hub_merged(repo_id, self.tokenizer, save_method="lora", token=token)elif save_method == "merged_16bit":self.model.push_to_hub_merged(repo_id, self.tokenizer, save_method="merged_16bit", token=token)elif save_method == "merged_4bit":self.model.push_to_hub_merged(repo_id, self.tokenizer, save_method="merged_4bit", token=token)elif save_method == "gguf":self.model.push_to_hub_gguf(repo_id,self.tokenizer,quantization_method=["q4_k_m", "q5_k_m"],token=token)else:raise ValueError(f"Unknown save method: {save_method}")print(f"Model successfully pushed to: https://huggingface.co/{repo_id}")return f"https://huggingface.co/{repo_id}"```### 2. PromptCreator```pythonclass PromptCreator:"""Creates and formats prompts for multiple choice questions"""# Prompt typesBASIC = "basic" # Simple answer-only formatYAML_REASONING = "yaml" # YAML formatted reasoningTEACHER_REASONED = "teacher" # Same YAML format but using teacher completionsdef __init__(self, prompt_type=BASIC):if prompt_type == self.TEACHER_REASONED:prompt_type = self.YAML_REASONINGself.prompt_type = prompt_typeself.original_type = prompt_typedef format_choices(self, choices):"""Format choices as a lettered list"""return "\n".join([f"{chr(65 + i)}. {choice}" for i, choice in enumerate(choices)])def get_max_letter(self, choices):"""Get the maximum letter based on number of choices"""return chr(65 + len(choices) - 1)def create_inference_prompt(self, question, choices):"""Create a prompt for inference based on current prompt type"""formatted_choices = self.format_choices(choices)max_letter = self.get_max_letter(choices)if self.prompt_type == self.YAML_REASONING:return self._create_yaml_prompt(question, formatted_choices, max_letter)else:return self._create_basic_prompt(question, formatted_choices, max_letter)def _create_basic_prompt(self, question, formatted_choices, max_letter):"""Create a basic prompt asking for just the answer letter"""return f"""QUESTION:{question}CHOICES:{formatted_choices}Answer with a single letter from A through {max_letter} without any additional explanation or commentary."""def _create_yaml_prompt(self, question, formatted_choices, max_letter):"""Create a prompt requesting YAML-formatted reasoning"""return f"""QUESTION:{question}CHOICES:{formatted_choices}Analyze this question step-by-step and provide a detailed explanation.Your response MUST be in YAML format as follows:understanding: |<your understanding of what the question is asking>analysis: |<your analysis of each option>reasoning: |<your step-by-step reasoning process>conclusion: |<your final conclusion>answer: <single letter A through {max_letter}>The answer field MUST contain ONLY a single character letter."""def create_training_prompt(self, question, choices):"""Create a prompt for training with the current prompt type"""formatted_choices = self.format_choices(choices)max_letter = self.get_max_letter(choices)if self.prompt_type == self.YAML_REASONING:return self._create_yaml_training_prompt(question, formatted_choices, max_letter)else:return self._create_basic_training_prompt(question, formatted_choices, max_letter)def _create_basic_training_prompt(self, question, formatted_choices, max_letter):"""Create a basic training prompt"""return f"""QUESTION:{question}CHOICES:{formatted_choices}The answer is a single letter (A, B, C, etc.). Only provide ONE character as your answer:"""def _create_yaml_training_prompt(self, question, formatted_choices, max_letter):"""Create a YAML-formatted training prompt"""return f"""QUESTION:{question}CHOICES:{formatted_choices}Analyze this question step-by-step and provide a detailed explanation.Follow the YAML format in your response:understanding: |<your understanding of the question>analysis: |2 unmodified lines<your reasoning about the correct answer>conclusion: |<your final conclusion>answer: <single letter A through {max_letter}>"""def set_prompt_type(self, prompt_type):"""Set the prompt type"""self.original_type = prompt_typeif prompt_type == self.TEACHER_REASONED:passself.prompt_type = prompt_typereturn selfdef is_teacher_mode(self):"""Check if we're using teacher mode"""return self.original_type == self.TEACHER_REASONED```### 3. ResponseParser```pythonclass ResponseParser:"""Parser for model responses with support for different formats"""# Parser modesBASIC = "basic" # Extract single letter answerYAML = "yaml" # Parse YAML formatted response with reasoningdef __init__(self, parser_mode=BASIC):self.parser_mode = parser_modedef parse(self, response_text):"""Parse the model's response according to the current mode"""if self.parser_mode == self.YAML:return self._parse_yaml_response(response_text)else:return self._parse_basic_response(response_text)def _parse_basic_response(self, response_text):"""Parse basic response looking for a letter answer"""import re# Try to extract a single letter answer (A-Z)answer_match = re.search(r"(?:^|\s)([A-Z])(?:\s|$|\.)", response_text)if answer_match:answer = answer_match.group(1)else:# Take first character if it's a letterif response_text and response_text[0].isalpha():answer = response_text[0].upper()else:answer = None# For basic mode, we don't extract detailed reasoningreasoning = ""return answer, reasoningdef _parse_yaml_response(self, response_text):"""Parse YAML formatted response extracting answer and reasoning"""import reimport yaml# First try to find answer in YAML formatyaml_match = re.search(r"answer:\s*([A-Z])", response_text)if yaml_match:answer = yaml_match.group(1)else:# Fall back to basic extraction if YAML parsing failsanswer_match = re.search(r"(?:^|\s)([A-Z])(?:\s|$|\.)", response_text)if answer_match:answer = answer_match.group(1)elif response_text and response_text[0].isalpha():answer = response_text[0].upper()else:answer = None# Try to parse reasoning from YAML formatreasoning = ""if "reasoning:" in response_text:yaml_content = yaml.safe_load("---\n" + response_text)if isinstance(yaml_content, dict) and "reasoning" in yaml_content:reasoning = yaml_content["reasoning"]# Add other YAML fields if availableif "understanding" in yaml_content:reasoning = f"Understanding: {yaml_content['understanding']}\n\n{reasoning}"if "conclusion" in yaml_content:reasoning = f"{reasoning}\n\nConclusion: {yaml_content['conclusion']}"else:# Use the full response as reasoning if not in YAML formatreasoning = response_textreturn answer, reasoningdef set_parser_mode(self, parser_mode):"""Set the parser mode"""self.parser_mode = parser_modereturn self@classmethoddef from_prompt_type(cls, prompt_type):"""Create a parser instance with mode matching the prompt type"""if prompt_type == PromptCreator.YAML_REASONING or prompt_type == PromptCreator.TEACHER_REASONED:return cls(parser_mode=cls.YAML)else:return cls(parser_mode=cls.BASIC)```### 4. MultipleChoiceTester```pythonclass MultipleChoiceTester:"""Framework for testing Qwen models on multiple choice questions"""def __init__(self, model_handler, prompt_creator=None):self.model_handler = model_handlerself.prompt_creator = prompt_creator or PromptCreator(PromptCreator.BASIC)self.response_parser = ResponseParser.from_prompt_type(self.prompt_creator.prompt_type)def infer_example(self, example, temperature=0.7, max_tokens=1024, prompt_type=None, stream=False):"""Inference on a single example for visualization/demonstration"""# Allow temporary override of prompt typeoriginal_prompt_type = Noneif prompt_type is not None:original_prompt_type = self.prompt_creator.prompt_typeself.prompt_creator.set_prompt_type(prompt_type)self.response_parser = ResponseParser.from_prompt_type(prompt_type)# Prepare dataquestion = example["question"]# Handle different formats of choicesif isinstance(example["choices"], list):choices = example["choices"]elif isinstance(example["choices"], str) and example["choices"].startswith("["):import astchoices = ast.literal_eval(example["choices"]) if "[" in example["choices"] else example["choices"].split(",")else:choices = str(example["choices"]).split(",")# Generate the prompt using prompt creatorprompt = self.prompt_creator.create_inference_prompt(question, choices)# Start timingstart_time = time.time()if stream:# Use streaming generationstreamer = self.model_handler.generate_with_streaming(prompt=prompt,temperature=temperature,max_tokens=max_tokens,stream=True)# Collect output from streamerraw_response = ""print("Model response:")for text_chunk in streamer:print(text_chunk, end="", flush=True)raw_response += text_chunkprint("\n")else:# Generate without streamingraw_response = self.model_handler.generate_with_streaming(prompt=prompt,temperature=temperature,max_tokens=max_tokens,stream=False)response_time = time.time() - start_time# Parse the response using the response parserpredicted_answer, reasoning = self.response_parser.parse(raw_response)# Prepare resultsresult = {"question": question,"choices": choices,"predicted_answer": predicted_answer,"reasoning": reasoning,"response_time": response_time,"raw_response": raw_response,"prompt_type": self.prompt_creator.prompt_type,}# Add task_id if availableif "task_id" in example:result["task_id"] = example["task_id"]# Calculate metrics if label is providedif "answer" in example:label = example["answer"]result["correct_answer"] = labelresult["is_correct"] = predicted_answer == label# Calculate perplexity if requestedif hasattr(self.model_handler, "calculate_perplexity"):perplexity = self.model_handler.calculate_perplexity(prompt, raw_response)result["perplexity"] = perplexity# Restore original prompt type if it was overriddenif original_prompt_type is not None:self.prompt_creator.set_prompt_type(original_prompt_type)self.response_parser = ResponseParser.from_prompt_type(original_prompt_type)return resultdef infer_batch(self, examples, temperature=0.7, max_tokens=1024, prompt_type=None, batch_size=4):"""Inference on a batch of examples"""# Allow temporary override of prompt typeoriginal_prompt_type = Noneif prompt_type is not None:original_prompt_type = self.prompt_creator.prompt_typeself.prompt_creator.set_prompt_type(prompt_type)self.response_parser = ResponseParser.from_prompt_type(prompt_type)# Prepare all promptsprompts = []metadata = []for i, example in enumerate(examples):# Extract dataquestion = example["question"]# Handle different formats of choicesif isinstance(example["choices"], list):choices = example["choices"]elif isinstance(example["choices"], str) and example["choices"].startswith("["):import astchoices = ast.literal_eval(example["choices"]) if "[" in example["choices"] else example["choices"].split(",")else:choices = str(example["choices"]).split(",")# Generate the prompt using prompt creatorprompt = self.prompt_creator.create_inference_prompt(question, choices)prompts.append(prompt)# Store metadata for latermeta = {"question": question,"choices": choices,"index": i,}# Add label if availableif "answer" in example:meta["label"] = example["answer"]if "task_id" in example:meta["task_id"] = example["task_id"]metadata.append(meta)# Process in batchesresults = []correct_count = 0total_count = 0perplexities = []for i in range(0, len(prompts), batch_size):batch_prompts = prompts[i:i+batch_size]batch_meta = metadata[i:i+batch_size]# Process batchstart_time = time.time()batch_responses = []for prompt in batch_prompts:response = self.model_handler.generate_with_streaming(prompt=prompt,temperature=temperature,max_tokens=max_tokens,stream=False)batch_responses.append(response)batch_time = time.time() - start_time# Process each response in the batchfor j, (response, meta) in enumerate(zip(batch_responses, batch_meta)):# Parse responsepredicted_answer, reasoning = self.response_parser.parse(response)# Create resultresult = {"question": meta["question"],"choices": meta["choices"],"predicted_answer": predicted_answer,"reasoning": reasoning,"raw_response": response,"prompt_type": self.prompt_creator.prompt_type,"response_time": batch_time / len(batch_prompts),}# Add task_id if availableif "task_id" in meta:result["task_id"] = meta["task_id"]# Add metrics if label availableif "label" in meta:label = meta["label"]result["correct_answer"] = labelresult["is_correct"] = predicted_answer == label# Update counts for accuracytotal_count += 1if result["is_correct"]:correct_count += 1# Calculate perplexity if possibleif hasattr(self.model_handler, "calculate_perplexity"):prompt = batch_prompts[j]perplexity = self.model_handler.calculate_perplexity(prompt, response)result["perplexity"] = perplexityperplexities.append(perplexity)results.append(result)# Calculate aggregate metricssummary_metrics = {}if total_count > 0:summary_metrics["accuracy"] = correct_count / total_countsummary_metrics["correct_count"] = correct_countsummary_metrics["total_count"] = total_countif perplexities:summary_metrics["avg_perplexity"] = sum(perplexities) / len(perplexities)summary_metrics["min_perplexity"] = min(perplexities)summary_metrics["max_perplexity"] = max(perplexities)# Restore original prompt type if it was overriddenif original_prompt_type is not None:self.prompt_creator.set_prompt_type(original_prompt_type)self.response_parser = ResponseParser.from_prompt_type(original_prompt_type)return results, summary_metricsdef evaluate_dataset(self, dataset, temperature=0.7, max_tokens=1024, num_examples=None,verbose=True, prompt_type=None, batch_size=4, log_to_wandb=False):"""Inference on a whole dataset with metrics calculation"""# Allow overriding the prompt type for this evaluationoriginal_prompt_type = self.prompt_creator.prompt_typeif prompt_type is not None:self.prompt_creator.set_prompt_type(prompt_type)self.response_parser = ResponseParser.from_prompt_type(prompt_type)# Select subset if specifiedif num_examples is not None:dataset = dataset.select(range(min(num_examples, len(dataset))))results = []correct_count = 0total_count = 0perplexities = []# Process examples in batchesfor i in range(0, len(dataset), batch_size):batch_examples = dataset[i:i+batch_size]if verbose:batch_desc = f"Batch {i//batch_size + 1}/{(len(dataset) + batch_size - 1) // batch_size}"print(f"\nProcessing {batch_desc} with {len(batch_examples)} examples...")# Infer batchbatch_results, batch_metrics = self.infer_batch(examples=batch_examples,temperature=temperature,max_tokens=max_tokens,batch_size=batch_size)# Update metricsresults.extend(batch_results)if "correct_count" in batch_metrics:correct_count += batch_metrics["correct_count"]total_count += batch_metrics["total_count"]if verbose:batch_accuracy = batch_metrics["accuracy"]overall_accuracy = correct_count / total_countprint(f"Batch accuracy: {batch_accuracy:.2%}, Overall: {overall_accuracy:.2%} ({correct_count}/{total_count})")# Collect perplexitiesif "avg_perplexity" in batch_metrics:for result in batch_results:if "perplexity" in result:perplexities.append(result["perplexity"])# Calculate final accuracyaccuracy = correct_count / total_count if total_count > 0 else 0.0if verbose:prompt_type_str = self.prompt_creator.prompt_typeprint(f"\nFinal accuracy with {prompt_type_str} prompts: {accuracy:.2%} ({correct_count}/{total_count})")if perplexities:avg_perplexity = sum(perplexities) / len(perplexities)print(f"Average perplexity: {avg_perplexity:.4f}")# Prepare comprehensive summarysummary = {"accuracy": accuracy,"correct_count": correct_count,"total_count": total_count,"prompt_type": self.prompt_creator.prompt_type,"results": results,}# Add perplexity metrics if availableif perplexities:summary["avg_perplexity"] = sum(perplexities) / len(perplexities)summary["min_perplexity"] = min(perplexities)summary["max_perplexity"] = max(perplexities)# Log results to wandb if requestedif log_to_wandb and wandb.run is not None:metrics = {"test/accuracy": accuracy,"test/correct_count": correct_count,"test/total_count": total_count,}if perplexities:metrics["test/avg_perplexity"] = summary["avg_perplexity"]metrics["test/min_perplexity"] = summary["min_perplexity"]metrics["test/max_perplexity"] = summary["max_perplexity"]wandb.log(metrics)# Create a table of results for visualization if task_id existsif "task_id" in dataset.features:columns = ["task_id", "question", "correct_answer", "predicted_answer", "is_correct"]table = wandb.Table(columns=columns)for res in results[:min(100, len(results))]:table.add_data(res.get("task_id", "unknown"),res["question"][:100] + "...",res.get("correct_answer", ""),res.get("predicted_answer", ""),res.get("is_correct", False))wandb.log({"test_samples": table})# Restore original prompt typeself.prompt_creator.set_prompt_type(original_prompt_type)self.response_parser = ResponseParser.from_prompt_type(original_prompt_type)return summarydef save_results(self, results, output_dir="./results"):"""Save evaluation results to file"""os.makedirs(output_dir, exist_ok=True)timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")results_file = os.path.join(output_dir, f"results_{timestamp}.json")# Create serializable resultsserializable_results = {"accuracy": results.get("accuracy", 0.0),"correct_count": results.get("correct_count", 0),"total_count": results.get("total_count", 0),"timestamp": timestamp,"prompt_type": results.get("prompt_type", "unknown"),}# Add perplexity metrics if availableif "avg_perplexity" in results:serializable_results["avg_perplexity"] = results["avg_perplexity"]serializable_results["min_perplexity"] = results["min_perplexity"]serializable_results["max_perplexity"] = results["max_perplexity"]# Process individual resultsserializable_results["individual_results"] = []for result in results["results"]:# Skip perplexity in individual results to save spaceresult_copy = result.copy()if "perplexity" in result_copy:del result_copy["perplexity"]# Convert choices if neededchoices = result_copy["choices"]if not isinstance(choices, list):try:import astresult_copy["choices"] = ast.literal_eval(choices)except (SyntaxError, ValueError):passserializable_results["individual_results"].append(result_copy)# Save to filewith open(results_file, "w") as f:import jsonjson.dump(serializable_results, f, indent=2)print(f"Results saved to {results_file}")return results_file```</details>## Quick StartHere's a simple example of how to use the model:```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torch# Load the model and tokenizermodel_id = "tuandunghcmut/Qwen25_Coder_MultipleChoice"tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_id,torch_dtype=torch.bfloat16,device_map="auto",trust_remote_code=True)# Example questionquestion = "What is the correct way to open a file in Python for reading?"choices = ["open('file.txt', 'r')","file.open('file.txt', 'read')","read('file.txt')","File.open('file.txt')"]# Format the promptprompt = f"""QUESTION:{question}CHOICES:{chr(65 + i)}. {choice}for i, choice in enumerate(choices)}Answer with a single letter from A through {chr(65 + len(choices) - 1)} without any additional explanation or commentary."""# Generate responseinputs = tokenizer(prompt, return_tensors="pt").to(model.device)outputs = model.generate(**inputs, max_new_tokens=10)response = tokenizer.decode(outputs[0], skip_special_tokens=True)print(f"Model's answer: {response}")```## Advanced Usage### Using the MultipleChoiceTester FrameworkFor more advanced usage, you can use the provided `MultipleChoiceTester` framework:```pythonfrom save import QwenModelHandler, MultipleChoiceTester, PromptCreator# Initialize the model handlermodel_handler = QwenModelHandler(model_name="tuandunghcmut/Qwen25_Coder_MultipleChoice",max_seq_length=2048,quantization="4bit",device_map="auto")# Create a prompt creator with YAML reasoning formatprompt_creator = PromptCreator(PromptCreator.YAML_REASONING)# Initialize the testertester = MultipleChoiceTester(model_handler, prompt_creator=prompt_creator)# Example questionexample = {"question": "What is the correct way to open a file in Python for reading?","choices": ["open('file.txt', 'r')","file.open('file.txt', 'read')","read('file.txt')","File.open('file.txt')"],"answer": "A" # Optional ground truth}# Get prediction with reasoningresult = tester.infer_example(example, temperature=0.0001, stream=True)print(f"Predicted answer: {result['predicted_answer']}")print("Reasoning:")print(result['reasoning'])```### Batch ProcessingYou can also process multiple questions in batches:```python# List of examplesexamples = [{"question": "What is the correct way to open a file in Python for reading?","choices": ["open('file.txt', 'r')", "file.open('file.txt', 'read')", "read('file.txt')", "File.open('file.txt')"],"answer": "A"},# Add more examples...]# Process batchresults, metrics = tester.infer_batch(examples, batch_size=4)print(f"Batch accuracy: {metrics['accuracy']:.2%}")```### Streaming InferenceThe model supports streaming inference, which provides real-time output as the model generates its response. This is particularly useful for interactive applications and when you want to see the reasoning process in real-time.#### Basic Streaming UsageHere's how to use streaming inference:```python# Initialize model handler and tester as beforemodel_handler = QwenModelHandler(model_name="tuandunghcmut/Qwen25_Coder_MultipleChoice",max_seq_length=2048)tester = MultipleChoiceTester(model_handler)# Example with streamingexample = {"question": "Which Python method is used to remove whitespace from both ends of a string?","choices": ["strip()","trim()","clean()","remove_whitespace()"],"answer": "A"}# Enable streaming with stream=Trueresult = tester.infer_example(example,temperature=0.0001,max_tokens=1024,stream=True # Enable streaming)# The output will be printed in real-time as the model generates it# You can also access the complete response after generationprint("\nFinal result:")print(f"Predicted answer: {result['predicted_answer']}")print("Complete reasoning:")print(result['reasoning'])```#### Advanced Streaming Patterns##### 1. Custom Stream ProcessingYou can process the streamed output in custom ways:```pythondef process_stream(streamer):"""Custom stream processing function"""collected_text = ""for chunk in streamer:# Process each chunk as it arrivescollected_text += chunk# You can do custom processing here# For example, parse partial YAML, update UI, etc.yield chunk, collected_text# Use custom stream processingresult = tester.infer_example(example,temperature=0.0001,stream=True)# Process the stream with custom logicfor chunk, full_text in process_stream(result['stream']):# Do something with each chunkprint(f"Chunk: {chunk}")print(f"Full text so far: {full_text}")```##### 2. YAML Streaming with Real-time ParsingWhen using YAML reasoning format, you can parse the output as it streams:```pythonimport yamlfrom io import StringIOdef parse_yaml_stream(streamer):"""Parse YAML content as it streams"""buffer = StringIO()for chunk in streamer:buffer.write(chunk)try:# Try to parse the current buffer as YAMLyaml_content = yaml.safe_load(buffer.getvalue())if yaml_content:yield chunk, yaml_contentexcept yaml.YAMLError:# Not enough content for valid YAML yetcontinue# Use YAML streaming with parsingresult = tester.infer_example(example,temperature=0.0001,prompt_type=PromptCreator.YAML_REASONING,stream=True)# Process YAML content as it streamsfor chunk, yaml_content in parse_yaml_stream(result['stream']):if isinstance(yaml_content, dict):# Access YAML fields as they become availableif 'understanding' in yaml_content:print(f"Understanding: {yaml_content['understanding']}")if 'reasoning' in yaml_content:print(f"Reasoning: {yaml_content['reasoning']}")if 'answer' in yaml_content:print(f"Answer: {yaml_content['answer']}")```##### 3. Streaming with Progress TrackingYou can track generation progress and timing:```pythonimport timedef stream_with_progress(streamer):"""Stream with progress tracking"""start_time = time.time()tokens_generated = 0for chunk in streamer:tokens_generated += len(chunk.split())elapsed = time.time() - start_timetokens_per_second = tokens_generated / elapsed if elapsed > 0 else 0yield {'chunk': chunk,'tokens': tokens_generated,'tokens_per_second': tokens_per_second,'elapsed': elapsed}# Use streaming with progress trackingresult = tester.infer_example(example,temperature=0.0001,stream=True)for progress in stream_with_progress(result['stream']):print(f"Generated {progress['tokens']} tokens "f"({progress['tokens_per_second']:.2f} tokens/sec)")print(f"Chunk: {progress['chunk']}")```#### Implementation DetailsThe streaming implementation uses Unsloth's optimized inference with the following key features:1. **Efficient Token Generation**- Uses Unsloth's `FastLanguageModel` for optimized inference- Implements streaming using `TextIteratorStreamer`- Supports both greedy and temperature-based sampling2. **Memory Management**- Streams tokens without storing the entire response in memory- Efficiently handles long responses- Supports batch processing with streaming3. **Performance Optimizations**- Uses `use_cache=True` for faster generation- Implements `min_p` sampling for better quality- Supports 4-bit quantization for reduced memory usage4. **Error Handling**- Gracefully handles streaming interruptions- Provides partial results if generation is interrupted- Maintains context for resumed generationThe streaming output will show the model's reasoning process in real-time, including:- Understanding of the question- Analysis of each option- Step-by-step reasoning- Final conclusion- Answer selectionThis is particularly useful for:- Debugging model behavior- Creating interactive demos- Understanding the model's reasoning process- Providing immediate feedback to users- Building real-time applications## Model Features- **YAML-Based Reasoning**: The model provides structured reasoning in YAML format- **Multiple Prompt Types**: Supports both basic and YAML-formatted reasoning prompts- **Batch Processing**: Efficiently process multiple questions at once- **Performance Metrics**: Tracks accuracy, perplexity, and response times- **Streaming Support**: Real-time output streaming for interactive use## ExamplesCheck out the [example notebook](https://colab.research.google.com/drive/1YOUR_NOTEBOOK_ID) for more detailed usage examples and demonstrations.## ContributingContributions are welcome! Please feel free to submit a Pull Request.## LicenseThis project is licensed under the MIT License - see the LICENSE file for details.
README.md+1020-405