Of course! This is a fantastic question and a core part of the Hugging Face ecosystem's power. The official and most common procedure for sharing a model with custom code is to leverage the Hugging Face Hub and the trust_remote_code feature.
This process allows users to load your model using the familiar AutoModelForCausalLM.from_pretrained(...) command, while the Hub transparently handles the distribution of your custom code.
Here is the official, step-by-step procedure:
The Core Concept: trust_remote_code=True
When you call from_pretrained, the transformers library first downloads the model's config.json file. It looks inside this file to determine the model's architecture.
The "magic" happens when you tell the config.json to not only use a standard architecture but also to look for a specific Python file in the same repository and use a class from that file. When a user loads your model with trust_remote_code=True, they are giving the library permission to download and execute the Python code you've provided.
Step-by-Step Integration Guide
Let's assume you have a local directory that looks something like this:
/my-awesome-model/
├── my_modeling_code.py # Your custom Python code for the model
├── fine-tuned-weights.bin # The model weights
├── config.json # The model configuration
├── tokenizer.json # The tokenizer files
└── ... other files ...
Here's how to prepare it for the Hub.
Step 1: Organize Your Project Files
The key is to have your custom code in a .py file within the model's repository. The standard convention is to name it modeling_....py.
Your final repository structure on the Hugging Face Hub should look like this:
your-username/your-model-name/
├── README.md
├── config.json # **Crucial for auto-mapping**
├── modeling_your_model_name.py # Your custom model definition code
├── pytorch_model.bin # Your model's weights
├── tokenizer_config.json # Tokenizer configuration
├── tokenizer.json # Tokenizer data
└── special_tokens_map.json # Special tokens
Step 2: Modify Your Custom Code (modeling_your_model_name.py)
Ensure your custom Python file is self-contained and ready for distribution.
- Inherit from Transformers Base Classes: Your custom model class must inherit from a
transformers base class, like PreTrainedModel. Your Causal LM model should inherit from the appropriate base (e.g., LlamaPreTrainedModel if it's a Llama variant, or the generic PreTrainedModel).
- Use the Correct
_tied_weights_keys: If you are using weight tying (like tying input and output embeddings), make sure the _tied_weights_keys attribute is set correctly in your model class.
- Register for Auto-mapping (Important!): At the end of your
modeling_your_model_name.py file, you need to register your custom class with the AutoConfig so it can be found.
Here is a simplified example of what your modeling_your_model_name.py might look like:
# modeling_your_model_name.py
from transformers import PreTrainedModel, AutoConfig
from transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaConfig # Example import
# ... all your other necessary imports ...
import torch
from torch import nn
# Define your custom configuration if you have one
# If you just fine-tuned, you can often reuse the original config class
class YourModelConfig(LlamaConfig): # Inherit from a base config
model_type = "your_model_name" # Use a unique name for your model type
# Your custom model architecture
class YourModelForCausalLM(PreTrainedModel):
config_class = YourModelConfig # Link to your custom config
def __init__(self, config: YourModelConfig):
super().__init__(config)
# ... your custom layers, modifications, etc.
# For example, a custom attention mechanism or a new type of block
self.my_custom_layer = nn.Linear(config.hidden_size, config.hidden_size)
# ... rest of the original or custom architecture ...
def forward(self, ...):
# ... your custom forward pass ...
return ...
# =================================================================================
# CRUCIAL PART: Register your model with the AutoClasses
# =================================================================================
# This allows AutoModelForCausalLM.from_pretrained(...) to find your custom class.
AutoConfig.register("your_model_name", YourModelConfig)
# The key part that maps your model type to your custom class.
# The `...ForCausalLM` suffix is a convention.
AutoModelForCausalLM.register(YourModelConfig, YourModelForCausalLM)
Step 3: Modify Your config.json
This is the most critical step. You need to edit your config.json to tell transformers where to find your custom code. You do this by adding an auto_map section.
- Set
model_type: Make sure the model_type field matches the unique name you used in your code (e.g., "your_model_name").
- Add
auto_map: This dictionary maps the Auto class to the name of your custom Python class.
Your config.json should look like this:
{
"architectures": [
"YourModelForCausalLM"
],
"model_type": "your_model_name",
"auto_map": {
"AutoConfig": "modeling_your_model_name.YourModelConfig",
"AutoModelForCausalLM": "modeling_your_model_name.YourModelForCausalLM"
},
// ... all your other configuration parameters like hidden_size, vocab_size, etc.
}
"AutoModelForCausalLM": The Auto class the user will call.
"modeling_your_model_name.YourModelForCausalLM": The value points to [filename_without_.py].[ClassName].
Step 4: Upload to the Hugging Face Hub
Now that your files are structured correctly, you can upload them.
-
Install huggingface_hub:
pip install huggingface_hub
-
Log in:
huggingface-cli login
# or from a notebook/script
from huggingface_hub import login
login()
-
Push your model and tokenizer: The easiest way is to load your model and tokenizer locally from your files and then use the .push_to_hub() method.
from transformers import AutoTokenizer, AutoModelForCausalLM
# First, make sure you can load it locally by pointing to the directory
# This is a great way to test before you upload
model_path = "/path/to/my-awesome-model/"
# To load locally with custom code, you must pass trust_remote_code=True
# AND point to the specific python file with the --custom-models flag (if needed)
# The most robust way is to ensure the auto_map is correct and just do this:
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
# Now, push to the hub
hub_model_id = "your-username/your-model-name"
tokenizer.push_to_hub(hub_model_id)
model.push_to_hub(hub_model_id)
print(f"Model successfully pushed to: https://huggingface.co/{hub_model_id}")
Step 5: How People Will Use Your Model
That's it! Now, anyone (including you) can load your model with a single, simple command. You should clearly state in your README.md (model card) that trust_remote_code=True is required.
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "your-username/your-model-name"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=True, # This is the key for the user
# device_map="auto" # Optional: for multi-gpu
)
Advanced Path: Official Integration into transformers
If your model represents a completely new, foundational architecture (not just a fine-tune or minor modification) that would benefit the entire community, you could consider getting it merged directly into the transformers library.
This is a much more involved process:
- Open an Issue: Start a discussion on the
transformers GitHub repository.
- Follow Contribution Guidelines: Adhere strictly to the library's coding standards.
- Extensive Testing: You will need to write comprehensive tests for your model.
- Add Documentation: Create documentation and examples.
- Code Review: Your code will be reviewed by the Hugging Face team.
For your case (a fine-tuned model with additional code), the trust_remote_code method is the standard, official, and recommended procedure.