Llama-3.1-6B-25pct-Compressed-8B-EN-V1 / modeling_llama_recovered.py
Vincent-Daniel Yun
Llama-3.1-8B 25% Compressed V1 (E-AI, Built with Llama)
c0a5452 verified
Raw
History Blame Contribute Delete
1.91 kB
"""Custom loader for the compressed Llama-3.1 checkpoint.
A standard Llama with a reduced number of layers, plus two per-layer buffers
(`recover_scale`, `recover_bias`) applied at the start of each decoder layer's
forward. Layers carry scale=1, bias=0 where no correction is present.
Load with: AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True)
"""
import torch
import torch.nn as nn
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.models.llama.modeling_llama import (
LlamaForCausalLM, LlamaModel, LlamaDecoderLayer)
class LlamaRecoveredConfig(LlamaConfig):
model_type = "llama_recovered"
class RecoveredLlamaDecoderLayer(LlamaDecoderLayer):
def __init__(self, config, layer_idx):
super().__init__(config, layer_idx)
h = config.hidden_size
self.register_buffer("recover_scale", torch.ones(h), persistent=True)
self.register_buffer("recover_bias", torch.zeros(h), persistent=True)
def forward(self, hidden_states, *args, **kwargs):
s = self.recover_scale.to(hidden_states.dtype)
b = self.recover_bias.to(hidden_states.dtype)
hidden_states = hidden_states * s + b
return super().forward(hidden_states, *args, **kwargs)
class LlamaRecoveredModel(LlamaModel):
config_class = LlamaRecoveredConfig
_no_split_modules = ["RecoveredLlamaDecoderLayer"]
def __init__(self, config):
super().__init__(config)
self.layers = nn.ModuleList(
[RecoveredLlamaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
self.post_init()
class LlamaRecoveredForCausalLM(LlamaForCausalLM):
config_class = LlamaRecoveredConfig
_no_split_modules = ["RecoveredLlamaDecoderLayer"]
def __init__(self, config):
super().__init__(config)
self.model = LlamaRecoveredModel(config)
self.post_init()