For continued pretraining with temporal conditioning, we'll take a different approach that focuses on teaching the model to associate specific time periods with the content, style, and vocabulary from those eras. This is more efficient for your use case.
Here's how to implement continued pretraining with temporal information using Unsloth:
import torch
from datasets import Dataset
from transformers import TrainingArguments
from unsloth import FastLanguageModel
# 1. Prepare your data as a continuous text corpus with year markers
# Example structure for your dataset:
data = [
{"year": 1888, "text": "Full text from an 1888 diary or book..."},
{"year": 1925, "text": "Content from a 1925 source..."},
# ... thousands more examples ...
]
# 2. Create a preprocessing function that adds temporal markers
def add_temporal_markers(examples):
"""Add year markers to each text sample."""
processed_texts = []
for year, text in zip(examples["year"], examples["text"]):
# Add temporal marker at the beginning
marked_text = f"[YEAR={year}] {text}"
processed_texts.append(marked_text)
return {"processed_text": processed_texts}
# 3. Create and process the dataset
df = pd.DataFrame(data)
dataset = Dataset.from_pandas(df)
dataset = dataset.map(
add_temporal_markers,
batched=True,
remove_columns=['year', 'text']
)
# 4. Load the base model with Unsloth
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Qwen3-14B-Base-unsloth-bnb-4bit",
max_seq_length=2048,
load_in_4bit=True,
)
# 5. Configure for pretraining (not SFT)
model = FastLanguageModel.get_peft_model(
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",
)
# 6. Define a function to process and tokenize the data
def tokenize_function(examples):
return tokenizer(
examples["processed_text"],
truncation=True,
max_length=2048,
padding="max_length",
return_tensors="pt",
)
# 7. Tokenize the dataset
tokenized_dataset = dataset.map(
tokenize_function,
batched=True,
remove_columns=["processed_text"]
)
# 8. Set up the data collator for language modeling
from transformers import DataCollatorForLanguageModeling
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False # We want causal language modeling, not masked
)
# 9. Set up training arguments
training_args = TrainingArguments(
output_dir="qwen3_temporal_pretrain",
per_device_train_batch_size=1,
gradient_accumulation_steps=8,
num_train_epochs=1,
learning_rate=2e-4,
fp16=not torch.cuda.is_bf16_supported(),
bf16=torch.cuda.is_bf16_supported(),
logging_steps=10,
save_steps=500,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
warmup_steps=100,
)
# 10. Create the trainer for pretraining
from transformers import Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
data_collator=data_collator,
)
# 11. Train the model
trainer.train()
# 12. Save the model
model.save_pretrained("qwen3_temporal_pretrained")
tokenizer.save_pretrained("qwen3_temporal_pretrained")
Key Points for Continued Pretraining:
-
Temporal Markers: We directly embed the year information into the text using a marker like [YEAR=1888]. This teaches the model to associate different writing styles and content with specific time periods.
-
Causal Language Modeling: We're using standard language modeling (predicting the next token) rather than instruction tuning.
-
Data Organization: Each entry from your historical books and diaries is formatted with the year marker at the beginning. This teaches the model the temporal relationship without needing dialogue format.
Using the Pretrained Model:
After pretraining, you can use the model by providing the year tag at the beginning of your prompt:
from unsloth import FastLanguageModel
# Load the pretrained model
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="qwen3_temporal_pretrained",
max_seq_length=2048,
load_in_4bit=True,
)
FastLanguageModel.for_inference(model)
# Test with different years
def generate_text(year, prompt):
input_text = f"[YEAR={year}] {prompt}"
inputs = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(
inputs.input_ids,
max_new_tokens=200,
temperature=0.7,
top_p=0.9,
)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
# Test with different years
print(generate_text(1850, "The recent advances in steam power have"))
print(generate_text(1925, "The most exciting new technology is"))
print(generate_text(1975, "People's opinions on computers are"))
This approach is more suitable for your task as it directly teaches the model to absorb and reproduce the styles, vocabulary, and knowledge from different time periods in a single continuous training process.