dont use the conversation system use continued pretraining
- User
dont use the conversation system use continued pretraining
Assistant
You're right! For continued pretraining, you want the model to learn the relationship between years and writing styles through exposure to raw text, not through conversation-style training. Here's how to set up continued pretraining with year-conditioned text generation:
1) Data Format for Continued Pretraining
Instead of instruction/output pairs, format your data as continuous text blocks with year prefixes:
[ { "text": "Year: 1888\n\nThe mechanical marvels of our age, while impressive in their ingenuity, seem to lack a certain soul. The steam engine thunders through our countryside, the telegraph carries messages across vast distances in mere moments, yet I cannot help but wonder if we are losing something essential in our haste toward progress. The craftsman's careful hand, the time spent in contemplation—these seem increasingly obsolete in our mechanized world." }, { "text": "Year: 1955\n\nThe atom has been split, and with it, our understanding of the world has fundamentally changed. What once seemed like the stuff of science fiction—unlimited energy, weapons of unimaginable destruction—is now our reality. We stand at a crossroads where the same force that could power our cities for generations could also reduce them to ash in minutes." }, { "text": "Year: 1692\n\nThe witch trials have cast a dark shadow over our village. Neighbor suspects neighbor, and fear has taken root where once there was trust. Goodwife Proctor was taken yesterday, though I have known her these many years to be a woman of virtue and Christian devotion. The magistrates seem convinced that the Devil walks among us, but I fear it is madness, not supernatural evil, that has taken hold of our community." } ]Key points:
- Each text block starts with "Year: XXXX"
- Include substantial text from that period (several paragraphs)
- Maintain the original writing style, vocabulary, and concerns of the era
- You can concatenate multiple excerpts from the same year in one text block
2) Loading and Preparing the Model
from unsloth import FastLanguageModel from transformers import AutoTokenizer model_name = "unsloth/Qwen3-14B-Base-unsloth-bnb-4bit" model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_name, max_seq_length=2048, load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype="float16", device_map="auto", ) # Add padding token if it doesn't exist if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token3) Continued Pretraining Setup
import torch from datasets import load_dataset from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from transformers import TrainingArguments, Trainer, DataCollatorForLanguageModeling # Prepare model for LoRA model = prepare_model_for_kbit_training(model) lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "up_proj", "down_proj"] ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() # Load and tokenize dataset dataset = load_dataset("json", data_files="historical_texts.json", split="train") def tokenize_function(examples): # Tokenize the text tokenized = tokenizer( examples["text"], truncation=True, padding=False, # Don't pad here, let the data collator handle it max_length=2048, return_tensors=None ) # For causal LM, labels are the same as input_ids tokenized["labels"] = tokenized["input_ids"].copy() return tokenized tokenized_dataset = dataset.map( tokenize_function, batched=True, remove_columns=dataset.column_names ) # Data collator for language modeling data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False, # We're doing causal LM, not masked LM pad_to_multiple_of=8, # For efficiency ) # Training arguments training_args = TrainingArguments( output_dir="qwen3-historical-continued-pretrain", overwrite_output_dir=True, per_device_train_batch_size=1, gradient_accumulation_steps=8, learning_rate=1e-4, # Lower LR for continued pretraining max_steps=2000, logging_steps=50, save_steps=500, save_total_limit=3, fp16=True, optim="adamw_paged", lr_scheduler_type="cosine", warmup_ratio=0.05, group_by_length=True, dataloader_drop_last=True, gradient_checkpointing=True, ) # Create trainer trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_dataset, data_collator=data_collator, tokenizer=tokenizer, ) # Train trainer.train() # Save the model model.save_pretrained("qwen3-historical-continued-pretrain") tokenizer.save_pretrained("qwen3-historical-continued-pretrain")4) Advanced Data Preparation Tips
A) Concatenating Multiple Texts:
def create_long_sequences(examples): """Concatenate multiple short texts to create longer training sequences""" concatenated = [] current_text = "" for text in examples["text"]: if len(current_text) + len(text) < 1500: # Leave room for tokenization current_text += text + "\n\n" else: if current_text: concatenated.append(current_text.strip()) current_text = text + "\n\n" if current_text: concatenated.append(current_text.strip()) return {"text": concatenated}B) Year-Based Sampling: If you want to ensure balanced representation across time periods:
# Group texts by year and sample evenly from collections import defaultdict import random def balance_by_year(dataset, samples_per_year=50): year_groups = defaultdict(list) for item in dataset: year = item["text"].split("\n")[0].replace("Year: ", "") year_groups[year].append(item) balanced_data = [] for year, texts in year_groups.items(): sampled = random.sample(texts, min(samples_per_year, len(texts))) balanced_data.extend(sampled) return balanced_data5) Testing the Model
After training, test with year-conditioned prompts:
def generate_text(model, tokenizer, year, prompt="", max_length=200): input_text = f"Year: {year}\n\n{prompt}" inputs = tokenizer(input_text, return_tensors="pt") with torch.no_grad(): outputs = model.generate( **inputs, max_length=max_length, temperature=0.8, do_sample=True, pad_token_id=tokenizer.eos_token_id ) return tokenizer.decode(outputs[0], skip_special_tokens=True) # Test examples print(generate_text(model, tokenizer, 1888, "The new inventions of our time")) print(generate_text(model, tokenizer, 1955, "The atomic age has begun")) print(generate_text(model, tokenizer, 1692, "The harvest this year"))6) Key Differences from SFT
- No instruction formatting: Just raw text with year prefixes
- Causal language modeling: The model learns to predict the next token given the context
- Lower learning rate: Continued pretraining typically uses lower LRs than fine-tuning
- Longer sequences: You can use longer text sequences since you're not limited by conversation turns
- Natural text flow: The model learns to naturally continue text in the style of the given period
This approach will teach your model to associate years with appropriate writing styles, vocabulary, and thematic concerns through exposure to period-appropriate text, rather than through explicit instruction-following training.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.