import torch import torch.nn as nn import torch.nn.functional as F from transformers…
- User
import torch import torch.nn as nn import torch.nn.functional as F from transformers import AutoModelForCausalLM, AutoTokenizer, get_linear_schedule_with_warmup, PreTrainedModel, AutoConfig, PretrainedConfig from torch.utils.data import Dataset, DataLoader from datasets import load_dataset from typing import Dict, List, Optional import numpy as np from tqdm import tqdm import wandb import logging import json from torch.amp import autocast, GradScaler
class ChainOfThoughtDataset(Dataset): def init(self, hf_dataset, tokenizer, max_length: int = 512, split="train", num_examples: Optional[int] = None): self.dataset = hf_dataset[split] if num_examples is not None: self.dataset = self.dataset.select(range(min(num_examples, len(self.dataset)))) self.tokenizer = tokenizer self.max_length = max_length
def __len__(self): return len(self.dataset) def __getitem__(self, idx): item = self.dataset[idx] document = item['document'] summary = item['summary'] input_text = f"Summarize: {document[:1000]}... Thought process:" target_text = f"1. Understand task\n2. Identify topics\n3. Extract key info\n4. Organize\n5. Condense\n6. Draft\n7. Review\n\nSummary: {summary[:100]}..." full_text = input_text + target_text encoded = self.tokenizer.encode_plus( full_text, max_length=self.max_length, padding="max_length", truncation=True, return_tensors="pt" ) input_ids = encoded["input_ids"].squeeze(0) attention_mask = encoded["attention_mask"].squeeze(0) target_start = len(self.tokenizer.encode(input_text, add_special_tokens=False)) labels = input_ids.clone() labels[:target_start] = -100 return { "input_ids": input_ids, "attention_mask": attention_mask, "labels": labels }class ThoughtModule(nn.Module): def init(self, hidden_size: int, num_heads: int = 4): super().init() self.self_attention = nn.MultiheadAttention(hidden_size, num_heads) self.norm = nn.LayerNorm(hidden_size) self.feed_forward = nn.Sequential( nn.Linear(hidden_size, hidden_size * 2), nn.GELU(), nn.Linear(hidden_size * 2, hidden_size) )
def forward(self, x): attended, _ = self.self_attention(x, x, x) x = self.norm(x + attended) return self.norm(x + self.feed_forward(x))class AdvancedChainOfThoughtConfig(PretrainedConfig): model_type = "advanced_cot"
def __init__( self, base_model_name="gpt2", num_thought_steps=3, **kwargs ): super().__init__(**kwargs) self.base_model_name = base_model_name self.num_thought_steps = num_thought_stepsclass AdvancedChainOfThoughtModel(PreTrainedModel): config_class = AdvancedChainOfThoughtConfig
def __init__(self, config): super().__init__(config) self.config = config # Load the base model for causal language modeling self.base_model = AutoModelForCausalLM.from_pretrained(config.base_model_name) # Load the tokenizer self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name, use_fast=True) self.tokenizer.pad_token = self.tokenizer.eos_token # Get hidden_size from the base model's configuration hidden_size = self.base_model.config.hidden_size # Thought modules based on the base model's hidden size self.thought_modules = nn.ModuleList([ThoughtModule(hidden_size) for _ in range(config.num_thought_steps)]) # Output layer to project hidden states to vocabulary size self.output_layer = nn.Linear(hidden_size, self.base_model.config.vocab_size) def forward(self, input_ids, attention_mask=None, labels=None): # Use the base model's transformer directly base_outputs = self.base_model.transformer(input_ids, attention_mask=attention_mask) hidden_states = base_outputs.last_hidden_state # Get last hidden states from the base model # Apply thought modules on top of the base model's hidden states for thought_module in self.thought_modules: hidden_states = thought_module(hidden_states) # Compute logits lm_logits = self.output_layer(hidden_states) # Compute loss if labels are provided loss = None if labels is not None: loss_fct = nn.CrossEntropyLoss() loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1)) return lm_logits, loss @torch.no_grad() def generate(self, input_ids, attention_mask=None, **kwargs): return self.base_model.generate(input_ids, attention_mask=attention_mask, **kwargs) def get_output_embeddings(self): return self.output_layer def set_output_embeddings(self, new_embeddings): self.output_layer = new_embeddings def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs): return self.base_model.prepare_inputs_for_generation(input_ids, past=past, **kwargs) def _reorder_cache(self, past, beam_idx): return self.base_model._reorder_cache(past, beam_idx) - Assistant
The error you're encountering is a result of trying to access the
hidden_sizeattribute from theAdvancedChainOfThoughtConfigobject, but it should instead be accessed from the configuration of the base model (gpt2). Let's fix this issue by ensuring that thehidden_sizeis retrieved from the configuration of thebase_modelafter it is instantiated, which is the source of this information.