import torch
from unsloth import FastLanguageModel
import optuna
from transformers import (TrainingArguments, TrainerCallback, Trainer,
DataCollatorForLanguageModeling)
from datasets import load_dataset
import torch.nn as nn
alpaca_cot_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request by reasoning through the answer step-by-step.
Instruction:
{}
Input:
{}
Response:
{}"""
EOS_TOKEN = tokenizer.eos_token
def formatting_prompts_func(examples):
instructions = examples["instruction"]
inputs = examples["input"]
outputs = examples["output"]
texts = []
for instruction, input_text, output in zip(instructions, inputs, outputs):
text = alpaca_cot_prompt.format(instruction, input_text, output) + EOS_TOKEN
texts.append(text)
code
# Tokenizasyon ve tensor üretimi
encoded = tokenizer(texts, truncation=True, padding='max_length',
max_length=max_seq_length, return_tensors="pt")
return {
"input_ids": encoded["input_ids"],
"attention_mask": encoded["attention_mask"],
"labels": torch.randint(0, 10, (encoded["input_ids"].size(0),)) # Örnek olarak rastgele etiketler
}
yukarıdaki kodumda aşağıdaki hatayı alıyorum bunu düzelt
AttributeError Traceback (most recent call last)
in <cell line: 171>()
169 # Optuna Study Oluşturma
170 study = optuna.create_study(direction='minimize')
--> 171 study.optimize(objective, n_trials=10)
172
173 # En İyi Hiperparametreleri Uygulama
15 frames
in forward(self, input_ids, attention_mask, **kwargs)
60 def forward(self, input_ids, attention_mask=None, **kwargs):
61 outputs = self.base_model(input_ids, attention_mask=attention_mask, **kwargs)
---> 62 last_hidden_state = outputs.last_hidden_state # Tensörü çıkarıyoruz
63
64 # Ortalama havuzlama yaparak sabit boyutlu bir vektör elde ediyoruz
AttributeError: 'CausalLMOutputWithPast' object has no attribute 'last_hidden_state'
The error you're encountering:
code
AttributeError: 'CausalLMOutputWithPast' object has no attribute 'last_hidden_state'
indicates that the output from self.base_model does not have an attribute named last_hidden_state. This typically happens because the model is configured to return different outputs, such as logits and past key values, but not the hidden states by default.
To resolve this issue, you'll need to adjust how you're accessing the hidden states from the model's output. Here's a step-by-step guide to fix the problem:
1. Enable Hidden States in the Base Model
First, ensure that your base model is configured to return the hidden states. This is essential because, by default, many causal language models (like GPT) do not return hidden states unless explicitly told to do so.
python
# Enable output of hidden states in the base model
base_model.config.output_hidden_states = True
2. Modify the forward Method to Access Hidden States
Once you've enabled hidden states in the configuration, update the forward method of your BayesianFastLanguageModel to correctly extract the last hidden state from the output.
Here's the revised forward method:
python
def forward(self, input_ids, attention_mask=None, **kwargs):
# Ensure hidden states are returned
outputs = self.base_model(
input_ids,
attention_mask=attention_mask,
output_hidden_states=True, # Explicitly request hidden states
**kwargs
)
# Access the last hidden state
if hasattr(outputs, 'hidden_states') and outputs.hidden_states:
last_hidden_state = outputs.hidden_states[-1] # Get the last layer's hidden state
else:
raise AttributeError("The model output does not contain 'hidden_states'. Please ensure that 'output_hidden_states' is set to True.")
# Perform mean pooling over the sequence length dimension
pooled_output = last_hidden_state.mean(dim=1) # Shape: [batch_size, hidden_size]
# Pass through the Bayesian output layer
logits = self.bayesian_output(pooled_output) # Shape: [batch_size, 10]
return logits
3. Ensure Compatibility with FastLanguageModel
Since you're using FastLanguageModel from the unsloth library (which isn't a standard Transformers model), make sure that it adheres to the Hugging Face Transformers' output structure. If FastLanguageModel behaves differently, you might need to adjust the attribute accesses accordingly.
4. Alternative Approach: Use outputs.last_hidden_state If Available
If after enabling hidden states you find that last_hidden_state is indeed part of the output, you can alternatively access it directly. However, based on standard Transformer behaviors, accessing via hidden_states is more reliable for custom models.
python
def forward(self, input_ids, attention_mask=None, **kwargs):
outputs = self.base_model(
input_ids,
attention_mask=attention_mask,
output_hidden_states=True,
**kwargs
)
# Try accessing last_hidden_state if it's available
if hasattr(outputs, 'last_hidden_state'):
last_hidden_state = outputs.last_hidden_state
elif hasattr(outputs, 'hidden_states') and outputs.hidden_states:
last_hidden_state = outputs.hidden_states[-1]
else:
raise AttributeError("The model output does not contain 'last_hidden_state' or 'hidden_states'.")
pooled_output = last_hidden_state.mean(dim=1)
logits = self.bayesian_output(pooled_output)
return logits
5. Final Adjustments and Testing
After making these changes:
Re-run your training script to ensure that the error is resolved.
Monitor the outputs to confirm that the hidden states are being correctly utilized.
Validate the model's performance to ensure that the Bayesian layers and other modifications are functioning as intended.
Complete Updated Code Snippet
Here's the full updated section of your code with the necessary modifications:
python
import torch
import torch.nn as nn
from unsloth import FastLanguageModel
import optuna
from transformers import (TrainingArguments, TrainerCallback, Trainer,
DataCollatorForLanguageModeling)
from datasets import load_dataset
# ... [Other parts of your code remain unchanged] ...
# Bayes yaklaşımlı modeli tanımlıyoruz
class BayesianFastLanguageModel(nn.Module):
def __init__(self, base_model):
super(BayesianFastLanguageModel, self).__init__()
self.base_model = base_model
# Enable output of hidden states
self.base_model.config.output_hidden_states = True
# Output Layer'ına Bayes uyguluyoruz
hidden_size = base_model.config.hidden_size # Gizli katman boyutunu alıyoruz
self.bayesian_output = BayesianLayer(hidden_size, 10) # Sınıflandırma için, 10 sınıf
# PEFT Modeli Ekleme (LoRA)
self.lora = FastLanguageModel.get_peft_model(
base_model,
r=16,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
lora_alpha=16,
lora_dropout=0,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=3407,
use_rslora=False,
loftq_config=None
)
def forward(self, input_ids, attention_mask=None, **kwargs):
# Ensure hidden states are returned
outputs = self.base_model(
input_ids,
attention_mask=attention_mask,
output_hidden_states=True, # Explicitly request hidden states
**kwargs
)
# Access the last hidden state
if hasattr(outputs, 'hidden_states') and outputs.hidden_states:
last_hidden_state = outputs.hidden_states[-1] # Get the last layer's hidden state
else:
raise AttributeError("The model output does not contain 'hidden_states'. Please ensure that 'output_hidden_states' is set to True.")
# Perform mean pooling over the sequence length dimension
pooled_output = last_hidden_state.mean(dim=1) # Shape: [batch_size, hidden_size]
# Pass through the Bayesian output layer
logits = self.bayesian_output(pooled_output) # Shape: [batch_size, 10]
return logits
# Instantiate the Bayesian model
model = BayesianFastLanguageModel(base_model)
# ... [Rest of your training and optimization code remains unchanged] ...
Additional Recommendations
Logging: Consider adding logging statements to verify that hidden_states are being correctly extracted.
Model Documentation: If FastLanguageModel has specific requirements or configurations for exposing hidden states, refer to its official documentation or source code to ensure compatibility.
Error Handling: The added error message helps in quickly identifying configuration issues related to hidden state outputs.
By making these adjustments, your model should correctly access the hidden states, and the AttributeError should be resolved. This will allow your Bayesian layers to function as intended, enabling effective training and optimization of your language model.