Spaces:
No application file
No application file
Sidhant
refactor: remove deprecated files and update model configurations for Mistral-7B Instruct; streamline training and upload processes
748781a Download src/train.py from clanflare/mistral-7b-finetuning-scripts: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/train.py
- Command line
-
hf download hf://spaces/clanflare/mistral-7b-finetuning-scripts/src/train.py
-
curl -L -o train.py https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/train.py
13 kB
| import os | |
| import torch | |
| import psutil | |
| import time | |
| from datetime import datetime | |
| from datasets import load_dataset | |
| from transformers import ( | |
| AutoModelForCausalLM, | |
| AutoTokenizer, | |
| TrainingArguments, | |
| Trainer, | |
| DataCollatorForLanguageModeling | |
| ) | |
| from peft import ( | |
| LoraConfig, | |
| get_peft_model, | |
| TaskType, | |
| PeftType | |
| ) | |
| import wandb | |
| from tqdm import tqdm | |
| import logging | |
| from config import ModelConfig, TrainingConfig, HubConfig | |
| from huggingface_hub import HfApi, login | |
| # Set up logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.FileHandler("training.log"), | |
| logging.StreamHandler() | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| def get_memory_usage(): | |
| """Get current memory usage in GB.""" | |
| process = psutil.Process(os.getpid()) | |
| return process.memory_info().rss / 1024 / 1024 / 1024 # Convert to GB | |
| def create_prompt(example): | |
| """Create a prompt template for the model.""" | |
| return f"""### Instruction: {example['prompt']} | |
| ### Response: {example['response']}""" | |
| def preprocess_dataset(dataset, tokenizer, max_length=2048, batch_size=32): | |
| """Preprocess and tokenize the dataset in batches to manage memory.""" | |
| logger.info(f"Starting preprocessing with max_length={max_length}, batch_size={batch_size}") | |
| logger.info(f"Initial memory usage: {get_memory_usage():.2f} GB") | |
| # Get total number of examples | |
| total_examples = len(dataset) | |
| logger.info(f"Total examples to process: {total_examples}") | |
| # Initialize lists to store results | |
| all_input_ids = [] | |
| all_attention_mask = [] | |
| # Process in batches | |
| for i in tqdm(range(0, total_examples, batch_size), desc="Processing batches"): | |
| batch_end = min(i + batch_size, total_examples) | |
| batch = dataset[i:batch_end] | |
| # Create prompts for this batch | |
| texts = [create_prompt({"prompt": p, "response": r}) | |
| for p, r in zip(batch["prompt"], batch["response"])] | |
| # Tokenize batch with fixed padding | |
| try: | |
| tokenized = tokenizer( | |
| texts, | |
| padding="max_length", | |
| truncation=True, | |
| max_length=max_length, | |
| return_tensors="pt" | |
| ) | |
| # Append to results | |
| all_input_ids.append(tokenized["input_ids"]) | |
| all_attention_mask.append(tokenized["attention_mask"]) | |
| # Log progress and shapes | |
| if (i // batch_size) % 10 == 0: | |
| logger.info(f"Processed {batch_end}/{total_examples} examples. Memory: {get_memory_usage():.2f} GB") | |
| logger.info(f"Batch shape: {tokenized['input_ids'].shape}") | |
| except Exception as e: | |
| logger.error(f"Error processing batch {i//batch_size}: {e}") | |
| continue | |
| # Concatenate all batches | |
| logger.info("Concatenating batches...") | |
| try: | |
| tokenized_dataset = { | |
| "input_ids": torch.cat(all_input_ids, dim=0), | |
| "attention_mask": torch.cat(all_attention_mask, dim=0) | |
| } | |
| logger.info(f"Final shapes - input_ids: {tokenized_dataset['input_ids'].shape}") | |
| except Exception as e: | |
| logger.error(f"Error concatenating batches: {e}") | |
| raise | |
| logger.info(f"Final memory usage: {get_memory_usage():.2f} GB") | |
| return tokenized_dataset | |
| class TextDataset(torch.utils.data.Dataset): | |
| def __init__(self, tokenized_data): | |
| self.input_ids = tokenized_data["input_ids"] | |
| self.attention_mask = tokenized_data["attention_mask"] | |
| def __len__(self): | |
| return len(self.input_ids) | |
| def __getitem__(self, idx): | |
| return { | |
| "input_ids": self.input_ids[idx], | |
| "attention_mask": self.attention_mask[idx] | |
| } | |
| def push_to_hub(model, tokenizer, hub_config): | |
| """Push the model and tokenizer to the Hugging Face Hub with privacy controls.""" | |
| logger.info(f"Pushing model to Hugging Face Hub: {hub_config.hub_model_id}") | |
| # Login to Hugging Face Hub | |
| if hub_config.hub_token: | |
| login(token=hub_config.hub_token) | |
| else: | |
| # Try to use token from environment variable | |
| login() | |
| # Create model card content | |
| model_card_content = f""" | |
| # {hub_config.hub_model_id} | |
| This model is a fine-tuned version of [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1) using LoRA. | |
| ## Model Details | |
| - **Base Model:** mistralai/Mistral-7B-v0.1 | |
| - **Fine-tuning Method:** LoRA (Low-Rank Adaptation) | |
| - **LoRA Rank:** 8 | |
| - **LoRA Alpha:** 16 | |
| - **Target Modules:** All attention and MLP layers | |
| ## Training Details | |
| - **Training Data:** Custom dataset | |
| - **Training Procedure:** Full precision training with bfloat16 | |
| - **Hardware:** NVIDIA H100 with 80GB VRAM | |
| - **Training Time:** ~2-3 hours for 3 epochs | |
| ## Usage | |
| ```python | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| # Load base model and tokenizer | |
| model_name = "mistralai/Mistral-7B-v0.1" | |
| model = AutoModelForCausalLM.from_pretrained(model_name) | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| # Load LoRA weights | |
| model = PeftModel.from_pretrained(model, "{hub_config.hub_model_id}") | |
| # Generate text | |
| inputs = tokenizer("### Instruction: Write a poem about AI\n\n### Response:", return_tensors="pt") | |
| outputs = model.generate(**inputs, max_length=200) | |
| print(tokenizer.decode(outputs[0])) | |
| ``` | |
| ## License | |
| {hub_config.hub_license} | |
| """ | |
| # Save model card | |
| #os.makedirs("model_card", exist_ok=True) | |
| #with open("model_card/README.md", "w") as f: | |
| # f.write(model_card_content) | |
| # Push to hub with privacy settings | |
| model.push_to_hub( | |
| hub_config.hub_model_id, | |
| private=hub_config.hub_private, | |
| commit_message=hub_config.hub_commit_message, | |
| token=hub_config.hub_token, | |
| organization=hub_config.hub_organization | |
| ) | |
| tokenizer.push_to_hub( | |
| hub_config.hub_model_id, | |
| private=hub_config.hub_private, | |
| commit_message=hub_config.hub_commit_message, | |
| token=hub_config.hub_token, | |
| organization=hub_config.hub_organization | |
| ) | |
| # Push model card | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj="model_card/README.md", | |
| path_in_repo="README.md", | |
| repo_id=hub_config.hub_model_id, | |
| token=hub_config.hub_token, | |
| commit_message="Add model card" | |
| ) | |
| # Add tags | |
| api.add_tags( | |
| repo_id=hub_config.hub_model_id, | |
| tags=hub_config.hub_tags, | |
| token=hub_config.hub_token | |
| ) | |
| logger.info(f"Successfully pushed model to {hub_config.hub_model_id}") | |
| logger.info(f"Model is {'private' if hub_config.hub_private else 'public'}") | |
| def download_and_verify_model(model_config: ModelConfig): | |
| """Download and verify the Mistral model with proper error handling.""" | |
| logger.info(f"Downloading model {model_config.model_name}...") | |
| try: | |
| # First try to load locally if available | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_config.model_name, | |
| torch_dtype=torch.bfloat16, # Use bfloat16 for H100 | |
| device_map="auto", | |
| use_flash_attention_2=True, # Enable Flash Attention 2 | |
| trust_remote_code=True, | |
| attn_implementation="flash_attention_2", # Use Flash Attention 2 | |
| cache_dir="models", # Store models in a dedicated directory | |
| resume_download=True, # Resume interrupted downloads | |
| low_cpu_mem_usage=True, # Optimize memory usage during loading | |
| return_dict=True, # Ensure we get dictionaries back | |
| use_cache=False # Disable KV cache for training | |
| ) | |
| # Prepare model for training | |
| model.config.use_cache = False # Disable KV cache during training | |
| model.train() # Set to training mode | |
| logger.info("Model loaded successfully!") | |
| return model | |
| except Exception as e: | |
| logger.error(f"Error loading model: {str(e)}") | |
| logger.error("Please ensure you have:") | |
| logger.error("1. Sufficient disk space (~15GB)") | |
| logger.error("2. Stable internet connection") | |
| logger.error("3. Hugging Face authentication if needed (use `huggingface-cli login`)") | |
| raise | |
| def get_timestamped_model_dir(): | |
| """Generate a timestamped directory name for model saving.""" | |
| timestamp = datetime.now().strftime("%d%m%y_%H%M%S") | |
| model_dir = f"models/mistral-7b-lora-finetuned-{timestamp}" | |
| os.makedirs(model_dir, exist_ok=True) | |
| return model_dir | |
| def main(): | |
| """Main training function.""" | |
| try: | |
| logger.info("Starting training pipeline") | |
| logger.info(f"Initial memory usage: {get_memory_usage():.2f} GB") | |
| # Initialize wandb | |
| wandb.init(project="mistral-7b-finetuning") | |
| # Create timestamped model directory | |
| model_dir = get_timestamped_model_dir() | |
| logger.info(f"Using model directory: {model_dir}") | |
| # Load tokenizer | |
| logger.info("Loading tokenizer...") | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| ModelConfig.model_name, | |
| trust_remote_code=True | |
| ) | |
| tokenizer.pad_token = tokenizer.eos_token | |
| tokenizer.padding_side = "right" | |
| # Load and preprocess dataset | |
| logger.info("Loading and preprocessing dataset...") | |
| dataset = load_dataset("json", data_files="../dataset.jsonl") | |
| tokenized_dataset = preprocess_dataset(dataset["train"], tokenizer) | |
| train_dataset = TextDataset(tokenized_dataset) | |
| logger.info(f"Dataset size: {len(train_dataset)} examples") | |
| # Load model | |
| logger.info("Loading model...") | |
| model = download_and_verify_model(ModelConfig) | |
| # Configure LoRA | |
| logger.info("Configuring LoRA...") | |
| lora_config = LoraConfig( | |
| r=8, | |
| lora_alpha=16, | |
| target_modules=[ | |
| "q_proj", | |
| "k_proj", | |
| "v_proj", | |
| "o_proj", | |
| "gate_proj", | |
| "up_proj", | |
| "down_proj", | |
| ], | |
| lora_dropout=0.05, | |
| bias="none", | |
| task_type=TaskType.CAUSAL_LM, | |
| inference_mode=False, | |
| modules_to_save=None, # Don't save any modules fully | |
| init_lora_weights=True, # Initialize LoRA weights | |
| peft_type=PeftType.LORA | |
| ) | |
| model = get_peft_model(model, lora_config) | |
| model.enable_input_require_grads() # Enable gradients for inputs | |
| model.print_trainable_parameters() # Print trainable parameters info | |
| # Training arguments | |
| training_args = TrainingArguments( | |
| output_dir=TrainingConfig.output_dir, | |
| num_train_epochs=TrainingConfig.num_train_epochs, | |
| per_device_train_batch_size=TrainingConfig.per_device_train_batch_size, | |
| gradient_accumulation_steps=TrainingConfig.gradient_accumulation_steps, | |
| learning_rate=TrainingConfig.learning_rate, | |
| max_grad_norm=TrainingConfig.max_grad_norm, | |
| warmup_ratio=TrainingConfig.warmup_ratio, | |
| lr_scheduler_type=TrainingConfig.lr_scheduler_type, | |
| logging_steps=TrainingConfig.logging_steps, | |
| save_steps=TrainingConfig.save_steps, | |
| eval_steps=TrainingConfig.eval_steps, | |
| save_total_limit=TrainingConfig.save_total_limit, | |
| fp16=TrainingConfig.fp16, | |
| bf16=TrainingConfig.bf16, | |
| optim=TrainingConfig.optim, | |
| gradient_checkpointing=TrainingConfig.gradient_checkpointing, | |
| report_to=TrainingConfig.report_to, | |
| torch_compile=TrainingConfig.torch_compile, | |
| ddp_find_unused_parameters=TrainingConfig.ddp_find_unused_parameters, | |
| push_to_hub=HubConfig.push_to_hub, | |
| hub_model_id=HubConfig.hub_model_id, | |
| hub_strategy="every_save", | |
| hub_token=HubConfig.hub_token | |
| ) | |
| # Initialize trainer | |
| trainer = Trainer( | |
| model=model, | |
| args=training_args, | |
| train_dataset=train_dataset, | |
| data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False) | |
| ) | |
| # Train | |
| logger.info("Starting training...") | |
| trainer.train() | |
| # Save the model | |
| logger.info("Saving model...") | |
| trainer.save_model(model_dir) | |
| tokenizer.save_pretrained(model_dir) | |
| # Push to Hub if enabled | |
| if HubConfig.push_to_hub: | |
| push_to_hub(model, tokenizer, HubConfig) | |
| logger.info(f"Training complete! Total time: {time.time() - start_time:.2f} seconds") | |
| except Exception as e: | |
| logger.error(f"Error in training pipeline: {e}", exc_info=True) | |
| raise | |
| if __name__ == "__main__": | |
| main() |