Write a GemmaMergeForCausalLM class, which inherits from PreTrainedModel, conducts logit level ensemble from 3 different GemmaForCausalLM class model, and can be loaded with AutoModelForCausalLM.from_pretrained
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course. Here is a complete, well-documented implementation of a GemmaMergeForCausalLM class that performs logit-level ensembling from three GemmaForCausalLM models and is fully compatible with the Hugging Face AutoModel ecosystem.
1. The Complete Code
This single file contains the custom configuration class, the main model class, and the necessary registration.
python
# gemma_merge_model.py
import torch
import torch.nn as nn
from typing import Optional, List, Union, Tuple
from transformers import (
PreTrainedModel,
AutoConfig,
AutoModelForCausalLM,
GemmaForCausalLM,
GemmaConfig,
)
from transformers.modeling_outputs import CausalLMOutputWithPast
from transformers.utils import logging
logger = logging.get_logger(__name__)
class GemmaMergeConfig(GemmaConfig):
"""
Configuration for the GemmaMergeForCausalLM model.
Inherits from GemmaConfig and adds paths to the constituent models.
"""
model_type = "gemma_merge"
def __init__(
self,
model_paths: Optional[List[str]] = None,
**kwargs,
):
super().__init__(**kwargs)
self.model_paths = model_paths if model_paths is not None else []
class GemmaMergeForCausalLM(PreTrainedModel):
"""
A Gemma model that performs logit-level ensembling from three different GemmaForCausalLM models.
This model loads three pre-trained Gemma models and averages their output logits to produce
a final, more robust prediction. It is designed to be a drop-in replacement for any
CausalLM model and can be loaded using `AutoModelForCausalLM.from_pretrained`.
"""
config_class = GemmaMergeConfig
def __init__(self, config: GemmaMergeConfig):
super().__init__(config)
if not config.model_paths or len(config.model_paths) != 3:
raise ValueError("GemmaMergeForCausalLM requires exactly 3 model paths in the config.")
# Use a ModuleList to properly register the sub-models
self.models = nn.ModuleList()
# Load the first model to get a reference configuration for compatibility checks
logger.info(f"Loading first model from: {config.model_paths[0]}")
first_model = AutoModelForCausalLM.from_pretrained(config.model_paths[0])
self.models.append(first_model)
reference_config = first_model.config
# Load the remaining models and check for configuration compatibility
for path in config.model_paths[1:]:
logger.info(f"Loading subsequent model from: {path}")
model = AutoModelForCausalLM.from_pretrained(path)
# --- Compatibility Checks ---
if model.config.vocab_size != reference_config.vocab_size:
raise ValueError(
f"Vocab size mismatch for model at {path}. "
f"Expected {reference_config.vocab_size}, got {model.config.vocab_size}"
)
if model.config.hidden_size != reference_config.hidden_size:
raise ValueError(
f"Hidden size mismatch for model at {path}. "
f"Expected {reference_config.hidden_size}, got {model.config.hidden_size}"
)
# Add other checks as needed (e.g., num_attention_heads)
self.models.append(model)
# Tie weights is handled by the post_init call from the parent class
self.post_init()
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, CausalLMOutputWithPast]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Get outputs from the first model. We will use its non-logit outputs
# (like past_key_values, hidden_states) as the template for the final output.
first_model_output = self.models[0](
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# Collect logits from all models
all_logits = [first_model_output.logits]
for model in self.models[1:]:
# We only need logits from the other models.
# Using torch.no_grad() can save memory during inference if the base models are frozen.
with torch.no_grad():
output = model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
)
all_logits.append(output.logits)
# Perform logit-level ensemble (averaging)
averaged_logits = torch.stack(all_logits, dim=0).mean(dim=0)
loss = None
if labels is not None:
# Standard Causal LM loss calculation on the averaged logits
# We shift the logits and labels to align for the next-token prediction task
shift_logits = averaged_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
# Construct the final output object using the merged logits and
# other outputs from the first model.
if not return_dict:
output = (averaged_logits,) + first_model_output[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=averaged_logits,
past_key_values=first_model_output.past_key_values,
hidden_states=first_model_output.hidden_states,
attentions=first_model_output.attentions,
)
# --- Registration ---
# This is the crucial step that makes the model discoverable by AutoModelForCausalLM.
# It links the custom config class to the custom model class.
AutoModelForCausalLM.register(GemmaMergeConfig, GemmaMergeForCausalLM)
2. How to Use It: A Step-by-Step Example
Here's how you would use the code above to create, save, and load a merged model.
python
# example_usage.py
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from gemma_merge_model import GemmaMergeConfig, GemmaMergeForCausalLM
# --- Step 1: Choose your base models ---
# For this example, we'll use the same model three times, but in a real-world scenario,
# you would use three different fine-tuned checkpoints.
# Let's use a smaller model for quick demonstration.
MODEL_ID = "google/gemma-2b"
MODEL_PATHS = [
f"./{MODEL_ID}-1",
f"./{MODEL_ID}-2",
f"./{MODEL_ID}-3",
]
# --- Step 2: Save the base models locally (optional, but good for reproducibility) ---
# In a real case, these paths would point to your existing fine-tuned models.
# We'll just download and save them for this example.
print("--- Downloading and saving base models ---")
for i, path in enumerate(MODEL_PATHS):
print(f"Saving model {i+1} to {path}")
model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
model.save_pretrained(path)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
tokenizer.save_pretrained(path)
# --- Step 3: Create the custom configuration ---
print("\n--- Creating GemmaMergeConfig ---")
merge_config = GemmaMergeConfig(
model_paths=MODEL_PATHS,
# You can override any GemmaConfig parameter here if needed
# torch_dtype=torch.float16, # For example
)
# --- Step 4: Instantiate the merged model ---
print("\n--- Instantiating GemmaMergeForCausalLM ---")
# This will load the three models from disk
merged_model = GemmaMergeForCausalLM(merge_config)
# --- Step 5: Save the merged model ---
# This creates a directory with a `config.json` and the model weights.
print("\n--- Saving the merged model ---")
MERGED_MODEL_PATH = "./my_gemma_ensemble"
merged_model.save_pretrained(MERGED_MODEL_PATH)
# Also save the tokenizer from one of the base models
tokenizer.save_pretrained(MERGED_MODEL_PATH)
print(f"Merged model saved to {MERGED_MODEL_PATH}")
# --- Step 6: Load the merged model using AutoModelForCausalLM ---
print("\n--- Loading the merged model with AutoModelForCausalLM ---")
# This is the key test. The AutoModel class will read the config.json,
# see the "model_type": "gemma_merge", and use our registered class.
loaded_model = AutoModelForCausalLM.from_pretrained(MERGED_MODEL_PATH)
loaded_tokenizer = AutoTokenizer.from_pretrained(MERGED_MODEL_PATH)
print("Model loaded successfully!")
print(f"Model type: {type(loaded_model)}")
# --- Step 7: Test the loaded model ---
print("\n--- Running inference with the loaded model ---")
prompt = "The capital of France is"
inputs = loaded_tokenizer(prompt, return_tensors="pt").to(loaded_model.device)
with torch.no_grad():
outputs = loaded_model.generate(**inputs, max_new_tokens=10)
result = loaded_tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Prompt: {prompt}")
print(f"Generated: {result}")
# You can also check the logits directly
logits = loaded_model(**inputs).logits
print(f"\nShape of output logits: {logits.shape}")
3. How It Works: The Magic of AutoModel
GemmaMergeConfig: We create a custom configuration that inherits from GemmaConfig. This gives us all the standard Gemma parameters (like vocab_size, hidden_size) and lets us add our own, model_paths. The model_type = "gemma_merge" is the most critical part. This string is written into the config.json file when you call save_pretrained.
GemmaMergeForCausalLM:
The __init__ method loads the three models specified in the config and stores them in an nn.ModuleList. This is important so that PyTorch recognizes them as sub-modules, and their parameters are included when you call .save_pretrained().
The forward method is the core of the ensembling logic. It passes the inputs to each model, collects the logits, averages them, and then calculates the loss (if labels are provided) based on these averaged logits. It uses the non-logit outputs (like past_key_values) from the first model to maintain a consistent output structure.
AutoModelForCausalLM.register(GemmaMergeConfig, GemmaMergeForCausalLM): This is the registration line that connects everything. It tells the Hugging Face AutoModel factory: "Whenever you load a configuration that is an instance of GemmaMergeConfig (which you identify by the model_type in config.json), you must instantiate it using the GemmaMergeForCausalLM class."
When you call AutoModelForCausalLM.from_pretrained("./my_gemma_ensemble"):
It loads ./my_gemma_ensemble/config.json.
It sees "model_type": "gemma_merge".
It looks up "gemma_merge" in its internal mapping and finds our registered class.
It instantiates GemmaMergeConfig from the JSON file.
It passes this config object to GemmaMergeForCausalLM(config) to create the model.
It loads the weights from pytorch_model.bin or model.safetensors into the newly created model instance.