diff --git a/examples/transform/llama3_example.py b/examples/transform/llama3_example.py new file mode 100644 index 000000000..b868d4b2a --- /dev/null +++ b/examples/transform/llama3_example.py @@ -0,0 +1,84 @@ +from datasets import load_dataset +from transformers import AutoModelForCausalLM, AutoTokenizer + +from llmcompressor.modifiers.quantization import GPTQModifier +from llmcompressor.modifiers.transform import TransformModifier +from llmcompressor import oneshot + +# Select model and load it. +MODEL_ID = "meta-llama/Meta-Llama-3-8B-Instruct" + +model = AutoModelForCausalLM.from_pretrained( + MODEL_ID, + torch_dtype="auto", +) +tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + +# Select calibration dataset. +DATASET_ID = "HuggingFaceH4/ultrachat_200k" +DATASET_SPLIT = "train_sft" + +# Select number of samples. 512 samples is a good place to start. +# Increasing the number of samples can improve accuracy. +NUM_CALIBRATION_SAMPLES = 512 +MAX_SEQUENCE_LENGTH = 2048 + +# Load dataset and preprocess. +ds = load_dataset(DATASET_ID, split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]") +ds = ds.shuffle(seed=42) + + +def preprocess(example): + return { + "text": tokenizer.apply_chat_template( + example["messages"], + tokenize=False, + ) + } + + +ds = ds.map(preprocess) + + +# Tokenize inputs. +def tokenize(sample): + return tokenizer( + sample["text"], + padding=False, + max_length=MAX_SEQUENCE_LENGTH, + truncation=True, + add_special_tokens=False, + ) + + +ds = ds.map(tokenize, remove_columns=ds.column_names) + +# Configure the quantization algorithm to run. +# * quantize the weights to 4 bit with GPTQ with a group size 128 +recipe = [ + TransformModifier(), + GPTQModifier(targets="Linear", scheme="W4A16", ignore=["lm_head"]), +] + +# Apply algorithms. +oneshot( + model=model, + dataset=ds, + recipe=recipe, + pipeline="sequential", + max_seq_length=MAX_SEQUENCE_LENGTH, + num_calibration_samples=NUM_CALIBRATION_SAMPLES, +) + +# Confirm generations of the quantized model look sane. +print("\n\n") +print("========== SAMPLE GENERATION ==============") +input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to("cuda") +output = model.generate(input_ids, max_new_tokens=100) +print(tokenizer.decode(output[0])) +print("==========================================\n\n") + +# Save to disk compressed. +SAVE_DIR = MODEL_ID.split("/")[1] + "-W4A16-G128" +model.save_pretrained(SAVE_DIR, save_compressed=True) +tokenizer.save_pretrained(SAVE_DIR) diff --git a/src/llmcompressor/modifiers/transform/__init__.py b/src/llmcompressor/modifiers/transform/__init__.py new file mode 100644 index 000000000..6c65678af --- /dev/null +++ b/src/llmcompressor/modifiers/transform/__init__.py @@ -0,0 +1,3 @@ +# flake8: noqa + +from .transform import TransformModifier diff --git a/src/llmcompressor/modifiers/transform/template/quip.py b/src/llmcompressor/modifiers/transform/template/quip.py new file mode 100644 index 000000000..e39c32e6d --- /dev/null +++ b/src/llmcompressor/modifiers/transform/template/quip.py @@ -0,0 +1,40 @@ +from compressed_tensors.transform import TransformArgs, TransformConfig, TransformScheme + +QUIP = TransformConfig( + config_groups={ + "v": TransformScheme( + type="random-hadamard", + apply=[ + TransformArgs( + targets=["Linear"], + location="input", # non-mergable + ignore="lm_head", + ), + TransformArgs( + targets=["Linear"], + location="weight_input", + inverse=True, + ignore="lm_head", + ), + ], + randomize=True, + ), + "u": TransformScheme( + type="random-hadamard", + apply=[ + TransformArgs( + targets=["Linear"], + location="weight_output", + ignore="lm_head", + ), + TransformArgs( + targets=["Linear"], + location="output", # non-mergable + inverse=True, + ignore="lm_head", + ), + ], + randomize=True, + ), + } +) diff --git a/src/llmcompressor/modifiers/transform/template/spinquant.py b/src/llmcompressor/modifiers/transform/template/spinquant.py new file mode 100644 index 000000000..d628cbfd9 --- /dev/null +++ b/src/llmcompressor/modifiers/transform/template/spinquant.py @@ -0,0 +1,64 @@ +from compressed_tensors.transform import TransformArgs, TransformConfig, TransformScheme + +LLAMA_SPINQUANT = TransformConfig( + transform_groups={ + "R1": TransformScheme( + type="hadamard", + apply=[ + TransformArgs( + targets=["embed_tokens", "o_proj", "down_proj"], + location="weight_output", + ), + TransformArgs( + targets=[ + "q_proj", + "k_proj", + "v_proj", + "up_proj", + "gate_proj", + "lm_head", + ], + location="weight_input", + inverse=True, + ), + ], + ), + "R2": TransformScheme( + type="hadamard", + apply=[ + TransformArgs( + targets=["v_proj"], + location="weight_output", + ), + TransformArgs( + targets=["o_proj"], location="weight_input", inverse=True + ), + ], + ), + "R3": TransformScheme( + type="hadamard", + apply=[ + TransformArgs( + targets=["self_attn"], + location="k_cache", + ), + TransformArgs( + targets=["self_attn"], + location="q_attn", + ), + ], + ), + "R4": TransformScheme( + type="hadamard", + apply=[ + TransformArgs( + targets=["down_proj"], + location="input", + ), + TransformArgs( + targets=["down_proj"], location="weight_input", inverse=True + ), + ], + ), + } +) diff --git a/src/llmcompressor/modifiers/transform/transform.py b/src/llmcompressor/modifiers/transform/transform.py new file mode 100644 index 000000000..6b8e89927 --- /dev/null +++ b/src/llmcompressor/modifiers/transform/transform.py @@ -0,0 +1,51 @@ +from typing import Dict, Optional + +from compressed_tensors.transform import TransformScheme, apply_transform_config + +from llmcompressor.core import Event, EventType, State +from llmcompressor.modifiers import Modifier + +from .template.quip import QUIP + + +class TransformModifier(Modifier): + preset_config: Optional[str] = None + config_groups: Optional[Dict[str, TransformScheme]] = None + + # model validator to validate both preset and config groups are not provided + + def on_initialize(self, state: State, **kwargs) -> bool: + if self.preset_config is not None: + # import config template and customize to model + pass + + # config = TransformConfig(config_groups=self.config_groups) + config = QUIP + + apply_transform_config(state.model, config) + + return True + + def on_start(self, state: State, event: Event, **kwargs): + self.started_ = True + + def on_event(self, state: State, event: Event, **kwargs): + if event.type_ == EventType.CALIBRATION_EPOCH_START: + if not self.started_: + self.on_start(state, None) + + elif event.type_ == EventType.SEQUENTIAL_EPOCH_END: + pass + + elif event.type_ == EventType.CALIBRATION_EPOCH_END: + if not self.ended_: + self.on_end(state, None) + + def on_end(self, state: State, event: Event, **kwargs): + self.ended_ = True + + def on_finalize(self, state: State, **kwargs) -> bool: + if not self.ended_: + self.on_end(state, None) + + return True diff --git a/tests/llmcompressor/modifiers/transform/test_correctness.py b/tests/llmcompressor/modifiers/transform/test_correctness.py new file mode 100644 index 000000000..8fca9639b --- /dev/null +++ b/tests/llmcompressor/modifiers/transform/test_correctness.py @@ -0,0 +1,29 @@ +import pytest +import torch +from compressed_tensors.transform import apply_transform_config +from transformers import AutoModelForCausalLM + +from llmcompressor.modifiers.transform.template.quip import QUIP + + +@pytest.mark.parametrize( + "dtype,exp_max,exp_mse", [ + (torch.bfloat16, 1.1, 0.012), # constructing and running transforms in float32 can improve to (~0.6562, ~0.0055) # noqa: E501 + (torch.float32, 4e-4, 2e-9) + ] +) +def test_apply_correctness(dtype, exp_max, exp_mse): + model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Meta-Llama-3-8B-Instruct", device_map="cuda", torch_dtype=dtype + ) + + input = {k: v.to("cuda") for k, v in model.dummy_inputs.items()} + with torch.no_grad(): + true_output = model(**input) + + apply_transform_config(model, QUIP) + with torch.no_grad(): + output = model(**input) + + assert torch.max(true_output.logits - output.logits) <= exp_max + assert torch.nn.MSELoss()(output.logits, true_output.logits) <= exp_mse