import torch from transformers import DataCollatorForLanguageModeling from datasets…
- User
import torch
from transformers import DataCollatorForLanguageModeling from datasets import load_dataset from transformers import ( AutoModelForCausalLM, AutoTokenizer,
BitsAndBytesConfig,
TrainingArguments, Trainer, ) from peft import LoraConfig, get_peft_model from trl import SFTTrainer
model_name = 'mistralai/Mistral-7B-Instruct-v0.3'
Load the tokenizer tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) tokenizer.pad_token = tokenizer.eos_token tokenizer.pad_token_id = tokenizer.eos_token_id tokenizer.padding_side = 'right'
Load the base model model = AutoModelForCausalLM.from_pretrained( model_name, )
PEFT configuration (ensure it matches the initial training) peft_config = LoraConfig( lora_alpha=16, lora_dropout=0.05, r=16, bias="none", task_type="CAUSAL_LM", target_modules=['k_proj', 'q_proj', 'v_proj', 'o_proj', 'gate_proj', 'down_proj', 'up_proj'], )
model = get_peft_model(model, peft_config) model.config.pad_token_id = tokenizer.pad_token_id model.config.use_cache = False
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device)
dataset = load_dataset('json', data_files='/workspace/Untitled Folder 1/static/data/train!_instruct_ss.jsonl')
def preprocess_function(examples): texts = [] for conversations in examples['messages']: input_text = '' output_text = '' for message in conversations: role = message['role'] content = message['content'] if role == 'user': input_text += f"User: {content}\n" elif role == 'assistant': output_text += content combined_text = input_text.strip() + '\nAssistant: ' + output_text.strip() texts.append(combined_text) model_inputs = tokenizer(texts, padding=True, truncation=True, max_length=512) return model_inputs
preprocessed_dataset = dataset.map( preprocess_function, batched=True, remove_columns=dataset['train'].column_names, )
print(preprocessed_dataset['train'].column_names)
#set up training arguments and the SFTTrainer training_arguments = TrainingArguments( output_dir="./results_products", optim="paged_adamw_8bit", per_device_train_batch_size=4, gradient_accumulation_steps=4, per_device_eval_batch_size=4, logging_steps=25, save_steps=250, learning_rate=6e-5, max_steps=12500, warmup_steps=300, lr_scheduler_type="linear", report_to="wandb" )
data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False, pad_to_multiple_of=8 )
Initialize the trainer trainer = Trainer( model=model, args=training_arguments, train_dataset=preprocessed_dataset['train'], data_collator=data_collator, )
Continue with training trainer.train()
Раздели эту тетрадку на несколько страничек сгрупировывая по логической последовательности действий. Так же на этапе загрузки датасета покажи несколько аналитических показателей о нем
- Assistant
- User
Ты ничего не забыл? А подключение wandb где? А где механизм мержа и сохранения модели и токенизатора в конце обучения? Доделывай!
- Assistant
Certainly! Let's expand the notebook by adding the integration with Weights & Biases (wandb) for logging and metrics tracking, as well as incorporating model and tokenizer saving mechanisms after the training process. Here's how you can extend the notebook:
Section 8: Weights & Biases Integration
Setup Weights & Biases
# Make sure to install W&B if you haven't already by uncommenting the line below # !pip install wandb import wandb # Initialize W&B project wandb.init(project="Mistral-7B-Instruct", name="fine-tuning-session") # Ensure that model performance is logged to W&B training_arguments.report_to = "wandb" - User
Где мерж модели??? Где апи ключ wandb?????
- Assistant
I apologize for the oversight. Let’s include the process for merging the model using PEFT and adding the Weights & Biases (wandb) API key configuration. I'll also walk you through how to save your integrated model appropriately.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.