Spaces:
No application file
No application file
Download src/utils/model_setup.py from clanflare/mistral-7b-finetuning-scripts: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/utils/model_setup.py
- Command line
-
hf download hf://spaces/clanflare/mistral-7b-finetuning-scripts/src/utils/model_setup.py
-
curl -L -o model_setup.py https://huggingface.co/spaces/clanflare/mistral-7b-finetuning-scripts/resolve/main/src/utils/model_setup.py
1.4 kB
| import torch | |
| from transformers import ( | |
| AutoModelForCausalLM, | |
| AutoTokenizer, | |
| ) | |
| from peft import LoraConfig, get_peft_model | |
| from src.config import ModelConfig, LoraConfig | |
| def setup_model_and_tokenizer( | |
| model_config: ModelConfig, | |
| lora_config: LoraConfig, | |
| device_map: str = "auto" | |
| ): | |
| """ | |
| Set up the model and tokenizer with LoRA configuration for full-precision training. | |
| """ | |
| # Load tokenizer | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| model_config.model_name, | |
| trust_remote_code=True, | |
| padding_side="right", | |
| ) | |
| # Add padding token if it doesn't exist | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| # Load model in full precision | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_config.model_name, | |
| device_map=device_map, | |
| trust_remote_code=True, | |
| torch_dtype=torch.float32, # Explicitly set full precision | |
| ) | |
| # Prepare LoRA config | |
| peft_config = LoraConfig( | |
| r=lora_config.r, | |
| lora_alpha=lora_config.lora_alpha, | |
| target_modules=lora_config.target_modules, | |
| lora_dropout=lora_config.lora_dropout, | |
| bias=lora_config.bias, | |
| task_type=lora_config.task_type, | |
| ) | |
| # Apply LoRA | |
| model = get_peft_model(model, peft_config) | |
| model.print_trainable_parameters() | |
| return model, tokenizer |