Could you explain the code below in a way a novice could understand?
Code:
code
!pip install transformers torch huggingface_hub bitsandbytes
import json
import pandas as pd
from datasets import Dataset
from transformers import (
AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer,
DataCollatorForLanguageModeling, pipeline
)
import torch
import random
import numpy as np
from google.colab import files, drive
# ------------- Reproducibility Setup -------------
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(SEED)
# -----------------------------
# Step 1: Load and preprocess data
# -----------------------------
drive.mount('/content/drive')
with open("/content/drive/My Drive/AIVA POF/balanced_labeled_conversations.json", "r") as f:
data = json.load(f)
df = pd.DataFrame(data)
traits = ["witty", "sarcastic", "charming"]
df = df[df['trait'].isin(traits)].dropna(subset=["dialogue"])
def format_conversation_with_expert_token(row):
expert_token = f"[EXPERT: {row['trait'].upper()}]"
return f"{expert_token} <|user|> {row['dialogue']}\n<|assistant|>"
df["text"] = df.apply(format_conversation_with_expert_token, axis=1)
# -----------------------------
# Step 2: Tokenization and special token addition
# -----------------------------
model_checkpoint = "deepseek-ai/deepseek-moe-16b-base"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, trust_remote_code=True)
# Add expert control tokens explicitly
special_tokens = [f"[EXPERT: {trait.upper()}]" for trait in traits]
num_added = tokenizer.add_tokens(special_tokens)
print(f"Added {num_added} special tokens: {special_tokens}")
# Ensure pad_token is defined
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
def tokenize_data(batch):
return tokenizer(
batch["text"],
padding="max_length",
truncation=True,
max_length=512,
)
dataset = Dataset.from_pandas(df[["text"]])
tokenized_dataset = dataset.map(tokenize_data, batched=True, remove_columns=["text"])
# -----------------------------
# Step 3: Load model and resize embeddings
# -----------------------------
from transformers import BitsAndBytesConfig, AutoModelForCausalLM, TrainingArguments, Trainer
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
import torch
import os
# Configure 8-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
bnb_8bit_compute_dtype=torch.bfloat16,
bnb_8bit_quant_type="nf4",
bnb_8bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
model_checkpoint,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
device_map="auto",
quantization_config=bnb_config, # Use quantization_config instead of load_in_8bit
)
model.resize_token_embeddings(len(tokenizer))
# Prepare model for 8-bit training and add LoRA adapters
model = prepare_model_for_kbit_training(model)
lora_config = LoraConfig(
r=16, # LoRA attention dimension
lora_alpha=32, # Alpha parameter for LoRA scaling
target_modules=["q_proj", "v_proj"], # Modules to apply LoRA to
lora_dropout=0.05, # Dropout probability for LoRA layers
bias="none", # Bias type
task_type="CAUSAL_LM", # Task type
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -----------------------------
# Step 4: Training setup
# -----------------------------
output_dir = "./deepseek_moe_expert_prompting"
training_args = TrainingArguments(
output_dir=output_dir,
per_device_train_batch_size=1, # Reduced batch size
gradient_accumulation_steps=8, # Increased gradient accumulation steps
num_train_epochs=1,
save_steps=500,
logging_dir="./logs",
logging_steps=50,
do_eval=False,
report_to="none",
seed=SEED,
# Add checkpointing arguments
save_strategy="steps",
save_total_limit=2, # Keep up to 2 checkpoints
load_best_model_at_end=False, # We are not doing evaluation
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
tokenizer=tokenizer,
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
print("Starting training...")
# Check if a checkpoint exists to resume from
latest_checkpoint = None
if os.path.exists(output_dir):
# This assumes checkpoint directories are named like "checkpoint-XXX"
checkpoint_dirs = [d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d.startswith("checkpoint-")]
if checkpoint_dirs:
# Find the latest checkpoint based on step number
latest_checkpoint_dir = max(checkpoint_dirs, key=lambda d: int(d.split("-")[1]))
latest_checkpoint = os.path.join(output_dir, latest_checkpoint_dir)
print(f"Resuming from checkpoint: {latest_checkpoint}")
# Use resume_from_checkpoint if a checkpoint is found
trainer.train(resume_from_checkpoint=latest_checkpoint)
print("Training complete.")
trainer.save_model(output_dir)
tokenizer.save_pretrained(output_dir)
# -----------------------------
# Step 5: Load fine-tuned model for inference
# -----------------------------
model_path = "./deepseek_moe_expert_prompting"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
torch_dtype=torch.bfloat16,
device_map="auto"
)
model.eval()
device_id = 0 if torch.cuda.is_available() else -1
text_gen_pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=device_id,
)
# -----------------------------
# Step 6: Multi-expert weighted response generation
# -----------------------------
def generate_weighted_response(user_input, trait_weights, max_new_tokens=100):
"""
Generate a blended response from multiple trait experts using
explicit single-expert generations weighted according to trait_weights.
Args:
user_input (str): Input dialogue from user.
trait_weights (dict): { trait_name (str): weight (float between 0 and 1) }
Weights should sum to 1 for meaningful blending.
max_new_tokens (int): Max tokens to generate per expert.
Returns:
str: A blended string concatenating weighted expert outputs.
"""
valid_traits = set(traits)
for trait in trait_weights.keys():
if trait not in valid_traits:
raise ValueError(f"Trait '{trait}' unknown. Valid: {valid_traits}")
blended_pieces = []
for trait, weight in trait_weights.items():
if weight <= 0:
continue
prompt = f"[EXPERT: {trait.upper()}] <|user|> {user_input}\n<|assistant|>"
results = text_gen_pipe(
prompt,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=0.7,
)
generated = results[0]["generated_text"]
if "<|assistant|>" in generated:
response = generated.split("<|assistant|>", 1)[1].strip()
else:
response = generated.strip()
blended_pieces.append(f"[{trait.capitalize()} {weight*100:.0f}%] {response}")
blended_response = "\n\n".join(blended_pieces)
return blended_response
# -----------------------------
# Step 7: Interactive CLI for testing
# -----------------------------
if __name__ == "__main__":
print("🧠 DeepSeek-MoE | Personality AI Assistant (Multi-expert weighted blending)")
print("Available traits:", ", ".join(traits))
print("You can input weights for each trait, e.g. witty=0.6 charming=0.3 sarcastic=0.1")
print("Weights do not need to sum to 1; they will be normalized automatically.")
while True:
try:
trait_weights_input = input("\nEnter trait weights or type 'exit': ").strip()
if trait_weights_input.lower() == 'exit':
print("Exiting.")
break
weights = {}
parts = trait_weights_input.split()
for part in parts:
if '=' not in part:
raise ValueError("Weight format must be trait=weight")
trait_name, weight_str = part.split('=', 1)
trait_name = trait_name.lower()
if trait_name not in traits:
raise ValueError(f"Trait '{trait_name}' invalid. Choose from {traits}")
weight = float(weight_str)
if weight < 0:
raise ValueError("Weights must be non-negative")
weights[trait_name] = weight
if not weights:
print("❌ No valid weights provided, please try again.")
continue
total_weight = sum(weights.values())
if total_weight == 0:
print("❌ Total weight cannot be zero, please try again.")
continue
normalized_weights = {k: v / total_weight for k, v in weights.items()}
user_input = input("You: ").strip()
response = generate_weighted_response(user_input, normalized_weights)
print(f"\nBlended AI response:\n{response}")
except Exception as e:
print(f"⚠️ Error: {e}")
Sure! I'll explain this code in simple terms, step by step, assuming you're new to Python and machine learning. This code is about training and using a special AI language model that can take on different "expert" personalities (like witty, sarcastic, charming) and blend their responses based on weights you give.
Overview
The code:
Loads conversation data labeled by personality traits.
Prepares the data to teach a language model how to respond in those personalities.
Trains a big language model, using special techniques to save memory and train faster.
Lets you generate new responses by mixing the personalities according to weights you choose.
Creates a simple interactive program where you type which personalities and weights you want, then asks the AI assistant for a response.
transformers: For working with language AI models.
torch: The underlying machine learning framework (PyTorch).
huggingface_hub: Helps download/upload models.
bitsandbytes: A library for low-bit (like 8-bit) training to save memory.
2. Importing Packages and Setting Seed for Reproducibility
The code imports various Python packages:
json, pandas for data handling.
datasets, transformers for data and model work.
torch, numpy, random for deep learning and random number control.
Google Colab utilities (files, drive) to work with Google Drive.
python
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(SEED)
Setting the random seed means the results will be the same each time you run this code (helps with debugging and consistency).
3. Loading & Preparing Data
python
drive.mount('/content/drive')
with open("/content/drive/My Drive/AIVA POF/balanced_labeled_conversations.json", "r") as f:
data = json.load(f)
df = pd.DataFrame(data)
Loads your conversation data from a JSON file stored in Google Drive.
The data contains dialogues labeled with traits like "witty", "sarcastic", "charming".
Formats each dialogue by adding a special token indicating the "expert" personality before the text, and special tokens for user and assistant. That helps the model learn to respond with the right personality.
Converts all text data into tokens the model understands.
Pads or cuts tokens so each input is the same length (512 tokens max).
Creates a dataset ready for training.
6. Load Model, Resize Embeddings, and Prepare for Training with LoRA
python
from transformers import BitsAndBytesConfig, AutoModelForCausalLM
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
This part brings in advanced features:
BitsAndBytes allows loading the large model in 8-bit precision (uses less memory).
LoRA (Low-Rank Adaptation) enables efficient fine-tuning by only training a small number of parameters (adapters), instead of the whole big model. It saves time and memory.