Skip to content

Commit

Permalink
Merge branch 'casper-hansen:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
DreamGenX authored Apr 20, 2024
2 parents 6747282 + 4fc6cc0 commit ea8874a
Show file tree
Hide file tree
Showing 19 changed files with 597 additions and 60 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/docs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
- uses: actions/setup-python@v4
with:
python-version: 3.x
python-version: 3.11
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v3
with:
Expand All @@ -25,4 +25,4 @@ jobs:
restore-keys: |
mkdocs-material-docs
- run: pip install mkdocstrings-python mkdocs-material griffe-typingdoc
- run: mkdocs gh-deploy --force
- run: mkdocs gh-deploy --force
2 changes: 1 addition & 1 deletion awq/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = "0.2.2"
__version__ = "0.2.4"
from awq.models.auto import AutoAWQForCausalLM
3 changes: 3 additions & 0 deletions awq/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@
from .llava import LlavaAWQForCausalLM
from .mixtral import MixtralAWQForCausalLM
from .qwen2 import Qwen2AWQForCausalLM
from .gemma import GemmaAWQForCausalLM
from .stablelm import StableLmAWQForCausalLM
from .starcoder2 import Starcoder2AWQForCausalLM
7 changes: 7 additions & 0 deletions awq/models/auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
"baichuan": BaichuanAWQForCausalLM,
"llava": LlavaAWQForCausalLM,
"qwen2": Qwen2AWQForCausalLM,
"gemma": GemmaAWQForCausalLM,
"stablelm": StableLmAWQForCausalLM,
"starcoder2": Starcoder2AWQForCausalLM,
}


Expand Down Expand Up @@ -50,6 +53,7 @@ def from_pretrained(
trust_remote_code=True,
safetensors=True,
device_map=None,
download_kwargs=None,
**model_init_kwargs,
) -> BaseAWQForCausalLM:
model_type = check_and_get_model_type(
Expand All @@ -62,6 +66,7 @@ def from_pretrained(
trust_remote_code=trust_remote_code,
safetensors=safetensors,
device_map=device_map,
download_kwargs=download_kwargs,
**model_init_kwargs,
)

Expand All @@ -79,6 +84,7 @@ def from_quantized(
safetensors=True,
device_map="balanced",
offload_folder=None,
download_kwargs=None,
**config_kwargs,
) -> BaseAWQForCausalLM:
os.environ["AWQ_BATCH_SIZE"] = str(batch_size)
Expand All @@ -103,5 +109,6 @@ def from_quantized(
safetensors=safetensors,
device_map=device_map,
offload_folder=offload_folder,
download_kwargs=download_kwargs,
**config_kwargs,
)
37 changes: 34 additions & 3 deletions awq/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@
"baichuan": "AutoModelForCausalLM",
"llava": "AutoModelForVision2Seq",
"qwen2": "AutoModelForCausalLM",
"gemma": "AutoModelForCausalLM",
"stablelm": "AutoModelForCausalLM",
"starcoder2": "AutoModelForCausalLM",
}


Expand Down Expand Up @@ -135,6 +138,12 @@ def quantize(
"This argument avoids real quantization by only applying the scales without quantizing down to FP16."
),
] = False,
apply_clip: Annotated[
bool,
Doc(
"Whether to apply clipping to the model during quantization. Some models may perform better with this set to False."
),
] = True,
):
"""
The main quantization function that you can use to quantize your model.
Expand Down Expand Up @@ -172,6 +181,7 @@ def quantize(
duo_scaling,
modules_to_not_convert=self.quant_config.modules_to_not_convert,
export_compatible=export_compatible,
apply_clip=apply_clip,
)
self.quantizer.quantize()

Expand Down Expand Up @@ -289,6 +299,9 @@ def from_pretrained(
"A device map that will be passed onto the model loading method from transformers."
),
] = None,
download_kwargs: Annotated[
Dict, Doc("Used for configure download model"),
] = None,
**model_init_kwargs: Annotated[
Dict,
Doc(
Expand All @@ -299,7 +312,9 @@ def from_pretrained(
"""A method for initialization of pretrained models, usually in FP16."""
# Get weights path and quant config
model_weights_path, config, quant_config = self._load_config(
self, model_path, "", safetensors, trust_remote_code=trust_remote_code
self, model_path, "", safetensors,
trust_remote_code=trust_remote_code,
download_kwargs=download_kwargs
)

target_cls_name = TRANSFORMERS_AUTO_MAPPING_DICT[config.model_type]
Expand Down Expand Up @@ -382,6 +397,9 @@ def from_quantized(
str,
Doc("The folder ot offload the model to."),
] = None,
download_kwargs: Annotated[
Dict, Doc("Used for configure download model"),
] = None,
**config_kwargs: Annotated[
Dict,
Doc(
Expand All @@ -398,6 +416,7 @@ def from_quantized(
safetensors,
trust_remote_code,
max_seq_len=max_seq_len,
download_kwargs=download_kwargs,
**config_kwargs,
)

Expand Down Expand Up @@ -469,6 +488,7 @@ def _load_config(
safetensors=True,
trust_remote_code=True,
max_seq_len=4096,
download_kwargs=None,
**config_kwargs,
):
# [STEP 1] Download model if path is not a directory
Expand All @@ -478,8 +498,19 @@ def _load_config(
ignore_patterns.extend(["*.pt*", "*.bin*", "consolidated*"])
else:
ignore_patterns.append("*.safetensors*")

model_path = snapshot_download(model_path, ignore_patterns=ignore_patterns)

if download_kwargs is None:
download_kwargs = {}

if "ignore_patterns" in download_kwargs:
download_kwargs_ignore_patterns = download_kwargs.pop("ignore_patterns")

if isinstance(download_kwargs_ignore_patterns, str):
ignore_patterns.append(download_kwargs_ignore_patterns)
elif isinstance(download_kwargs_ignore_patterns, list):
ignore_patterns.extend(download_kwargs_ignore_patterns)

model_path = snapshot_download(model_path, ignore_patterns=ignore_patterns, **download_kwargs)

if model_filename != "":
model_weights_path = model_path + f"/{model_filename}"
Expand Down
149 changes: 149 additions & 0 deletions awq/models/gemma.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import tqdm
import torch
from typing import List, Tuple
from .base import BaseAWQForCausalLM
from awq.utils.fused_utils import fuse_qkv
from awq.modules.fused.block import LlamaLikeBlock
from awq.modules.fused.model import LlamaLikeModel
from transformers.models.gemma.modeling_gemma import (
GemmaDecoderLayer as OldGemmaDecoderLayer,
GemmaForCausalLM as OldGemmaForCausalLM,
)
from awq.modules.fused.norm import FasterTransformerRMSNorm


class GemmaAWQForCausalLM(BaseAWQForCausalLM):
layer_type = "GemmaDecoderLayer"
max_new_tokens_key = "max_position_embeddings"

@staticmethod
def fuse_layers(model: OldGemmaDecoderLayer):
fuser = GemmaFuser(model)
fuser.fuse_transformer()

@staticmethod
def get_model_layers(model: OldGemmaForCausalLM):
return model.model.layers

@staticmethod
def get_act_for_scaling(module: OldGemmaDecoderLayer):
return dict(is_scalable=False)

@staticmethod
def move_embed(model: OldGemmaForCausalLM, device: str):
model.model.embed_tokens = model.model.embed_tokens.to(device)

@staticmethod
def get_layers_for_scaling(module: OldGemmaDecoderLayer, input_feat, module_kwargs):
layers = []

# attention input
layers.append(
dict(
prev_op=module.input_layernorm,
layers=[
module.self_attn.q_proj,
module.self_attn.k_proj,
module.self_attn.v_proj,
],
inp=input_feat["self_attn.q_proj"],
module2inspect=module.self_attn,
kwargs=module_kwargs,
)
)

# attention out
# Please refer to https://github.com/mit-han-lab/llm-awq/pull/67#issue-1850622696
if module.self_attn.v_proj.weight.shape == module.self_attn.o_proj.weight.shape:
layers.append(
dict(
prev_op=module.self_attn.v_proj,
layers=[module.self_attn.o_proj],
inp=input_feat["self_attn.o_proj"],
)
)

# linear 1
layers.append(
dict(
prev_op=module.post_attention_layernorm,
layers=[module.mlp.gate_proj, module.mlp.up_proj],
inp=input_feat["mlp.gate_proj"],
module2inspect=module.mlp,
)
)

# linear 2
layers.append(
dict(
prev_op=module.mlp.up_proj,
layers=[module.mlp.down_proj],
inp=input_feat["mlp.down_proj"],
)
)

return layers


class GemmaFuser:
def __init__(self, model: OldGemmaForCausalLM):
self.model = model

self.Gemma_blocks: List[Tuple[str, OldGemmaDecoderLayer]] = [
(name, module)
for name, module in self.model.named_modules()
if "GemmaDecoderLayer".lower() in module.__class__.__name__.lower()
]

def fuse_transformer(self):
blocks = []

module: OldGemmaDecoderLayer
for module in tqdm.tqdm(self.model.model.layers, desc="Fusing layers..."):
device = next(iter(module.state_dict().values())).device
qkv = fuse_qkv(
module,
module.self_attn.q_proj,
module.self_attn.k_proj,
module.self_attn.v_proj,
)
with torch.no_grad():
# GemmaRMSNorm is different from Llama's in that it multiplies
# (1 + weight) to the output, instead of just weight.
module.input_layernorm.weight += 1
module.post_attention_layernorm.weight += 1
norm_1 = FasterTransformerRMSNorm(
module.input_layernorm.weight, module.input_layernorm.eps
)
norm_2 = FasterTransformerRMSNorm(
module.post_attention_layernorm.weight,
module.post_attention_layernorm.eps,
)
blocks.append(
LlamaLikeBlock(
hidden_size=self.model.config.hidden_size,
n_heads=self.model.config.num_attention_heads,
n_kv_heads=self.model.config.num_key_value_heads,
qkv_layer=qkv,
o_proj=module.self_attn.o_proj,
mlp=module.mlp,
norm_1=norm_1,
norm_2=norm_2,
dev=device,
max_seq_len=self.model.config.max_seq_len,
rope_theta=self.model.config.rope_theta,
head_dim=self.model.config.head_dim,
)
)

with torch.no_grad():
# Normalize Gemma's embedding layer
self.model.model.embed_tokens.weight *= self.model.config.hidden_size**0.5

self.model.model = LlamaLikeModel(
self.model.config.vocab_size,
blocks,
self.model.model.embed_tokens,
self.model.model.norm,
)
setattr(self.model.model, "blocks", self.model.model.blocks)
Loading

0 comments on commit ea8874a

Please sign in to comment.