|
| 1 | +from typing import List, Type, Union, Optional, Dict |
| 2 | + |
| 3 | +import argparse |
| 4 | + |
| 5 | +import torch |
| 6 | +import transformers |
| 7 | +from transformers import AutoProcessor, PreTrainedModel |
| 8 | + |
| 9 | +from llmcompressor.transformers import tracing |
| 10 | +from llmcompressor.utils.pytorch.module import get_no_split_params |
| 11 | +from llmcompressor.pipelines.sequential.helpers import trace_subgraphs |
| 12 | +from llmcompressor.transformers import DataTrainingArguments, TextGenerationDataset |
| 13 | + |
| 14 | + |
| 15 | +def parse_args(): |
| 16 | + parser = argparse.ArgumentParser(description="Trace a model into subgraphs") |
| 17 | + parser.add_argument("--model_id", type=str, required=True, help="The stub of the model to load") # noqa: E501 |
| 18 | + parser.add_argument("--model_class", type=str, required=True, help="The class name of the model") # noqa: E501 |
| 19 | + parser.add_argument("--sequential_targets", type=str, nargs="*", default=None, metavar="TARGET", help="List of targets for sequential tracing") # noqa: E501 |
| 20 | + parser.add_argument("--ignore", type=str, nargs="*", default=[], metavar="PATTERN", help="List of patterns to ignore during tracing") # noqa: E501 |
| 21 | + parser.add_argument("--modality", type=str, default="text", help="Modality of calibration dataset, defaults to text") # noqa: E501 |
| 22 | + return parser.parse_args() |
| 23 | + |
| 24 | + |
| 25 | +def trace( |
| 26 | + model_id: str, |
| 27 | + model_class: Type[PreTrainedModel], |
| 28 | + sequential_targets: Optional[Union[List[str], str]] = None, |
| 29 | + ignore: Union[List[str], str] = [], |
| 30 | + modality: str = "text", |
| 31 | +): |
| 32 | + """ |
| 33 | + Debug traceability by tracing a pre-trained model into subgraphs |
| 34 | +
|
| 35 | + :param model_id: stub of the model to load |
| 36 | + :param model_class: class constructor of the pre-trained model. Can use either |
| 37 | + HF transformers classes or `Traceable` classes defined by LLM Compressor |
| 38 | + :param sequential_targets: targets for sequential tracing, defaults to automatic |
| 39 | + inference |
| 40 | + :param ignore: patterns to ignore during tracing |
| 41 | + :param modality: data modality for dummy tracing data, defaults to 'text' |
| 42 | +
|
| 43 | + Example usage from CLI |
| 44 | + llmcompressor.trace \ |
| 45 | + --model_id Qwen/Qwen2-VL-2B-Instruct \ |
| 46 | + --model_class Qwen2VLForConditionalGeneration \ |
| 47 | + --sequential_targets Qwen2VLDecoderLayer \ |
| 48 | + --ignore "lm_head" "re:visual.*" \ |
| 49 | + --modality text |
| 50 | + """ |
| 51 | + # Load model |
| 52 | + model = model_class.from_pretrained( |
| 53 | + model_id, |
| 54 | + device_map="auto", |
| 55 | + torch_dtype="auto", |
| 56 | + ) |
| 57 | + processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True) |
| 58 | + print("Loaded model") |
| 59 | + |
| 60 | + # Prepare sample data |
| 61 | + data_args = DataTrainingArguments(**get_dataset_kwargs(modality)) |
| 62 | + dataset = TextGenerationDataset.load_from_registry( |
| 63 | + data_args.dataset, |
| 64 | + data_args=data_args, |
| 65 | + split=data_args.splits["calibration"], |
| 66 | + processor=processor, |
| 67 | + )(add_labels=False) |
| 68 | + sample_input = next(iter(dataset)) |
| 69 | + sample_input = {k: torch.tensor(v) for k, v in sample_input.items()} |
| 70 | + print("Loaded sample data") |
| 71 | + |
| 72 | + # infer sequential targets |
| 73 | + if sequential_targets is None: |
| 74 | + sequential_targets = get_no_split_params(model) |
| 75 | + if isinstance(sequential_targets, str): |
| 76 | + sequential_targets = [sequential_targets] |
| 77 | + |
| 78 | + # infer ignore |
| 79 | + if isinstance(ignore, str): |
| 80 | + ignore = [ignore] |
| 81 | + |
| 82 | + # Attempt trace |
| 83 | + print( |
| 84 | + "\nAttempting trace\n" |
| 85 | + f" model_id={model_id}\n" |
| 86 | + f" model_class={model_class.__name__}\n" |
| 87 | + f" dataset={data_args.dataset}\n" |
| 88 | + f" split={dataset.split}\n" |
| 89 | + f" inputs={sample_input.keys()}\n" |
| 90 | + f" sequential_targets={sequential_targets}\n" |
| 91 | + f" ignore={ignore}\n" |
| 92 | + ) |
| 93 | + subgraphs = trace_subgraphs(model, sample_input, sequential_targets, ignore) |
| 94 | + print(f"Successfully traced model into {len(subgraphs)} subgraphs!\n") |
| 95 | + |
| 96 | + |
| 97 | +def get_model_class(model_class: str) -> Type[PreTrainedModel]: |
| 98 | + model_cls = getattr(tracing, model_class, getattr(transformers, model_class, None)) |
| 99 | + if model_cls is None: |
| 100 | + raise ValueError(f"Could not import model class {model_class}") |
| 101 | + |
| 102 | + return model_cls |
| 103 | + |
| 104 | + |
| 105 | +def get_dataset_kwargs(modality: str) -> Dict[str, str]: |
| 106 | + dataset_kwargs = { |
| 107 | + "text": { |
| 108 | + "dataset": "ultrachat-200k", |
| 109 | + "splits": {"calibration": "test_sft[:1]"}, |
| 110 | + }, |
| 111 | + "vision": { |
| 112 | + "dataset": "flickr", |
| 113 | + "splits": {"calibration": "test[:1]"}, |
| 114 | + }, |
| 115 | + } |
| 116 | + |
| 117 | + if modality not in dataset_kwargs: |
| 118 | + raise ValueError(f"Modality must be one of {list(dataset_kwargs.keys())}") |
| 119 | + |
| 120 | + return dataset_kwargs[modality] |
| 121 | + |
| 122 | + |
| 123 | +def main(): |
| 124 | + args = parse_args() |
| 125 | + |
| 126 | + trace( |
| 127 | + model_id=args.model_id, |
| 128 | + model_class=get_model_class(args.model_class), |
| 129 | + sequential_targets=args.sequential_targets, |
| 130 | + ignore=args.ignore, |
| 131 | + modality=args.modality, |
| 132 | + ) |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + main() |
0 commit comments