|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Utilities for sparse attention integration with llm_eval.""" |
| 17 | + |
| 18 | +import modelopt.torch.sparsity.attention_sparsity as mtsa |
| 19 | + |
| 20 | +# Custom sparse attention configurations |
| 21 | +CUSTOM_SPARSE_CONFIG = { |
| 22 | + "SPARSE_CONSERVATIVE": { |
| 23 | + "sparse_cfg": { |
| 24 | + "*attn*": { |
| 25 | + "method": "flash_skip_softmax", |
| 26 | + "threshold": {"prefill": 5e-4, "decode": 1e-5}, |
| 27 | + "br": 128, |
| 28 | + "bc": 128, |
| 29 | + "backend": "pytorch", |
| 30 | + "enable": True, |
| 31 | + }, |
| 32 | + "default": {"enable": False}, |
| 33 | + }, |
| 34 | + }, |
| 35 | + "SPARSE_AGGRESSIVE": { |
| 36 | + "sparse_cfg": { |
| 37 | + "*attn*": { |
| 38 | + "method": "flash_skip_softmax", |
| 39 | + "threshold": {"prefill": 5e-3, "decode": 5e-4}, |
| 40 | + "br": 128, |
| 41 | + "bc": 128, |
| 42 | + "backend": "pytorch", |
| 43 | + "enable": True, |
| 44 | + }, |
| 45 | + "default": {"enable": False}, |
| 46 | + }, |
| 47 | + }, |
| 48 | +} |
| 49 | + |
| 50 | + |
| 51 | +def _extract_model(model_obj): |
| 52 | + """Extract actual model from wrapper (HFLM or EvalModel).""" |
| 53 | + if hasattr(model_obj, "gpt2"): |
| 54 | + return model_obj.gpt2 |
| 55 | + elif hasattr(model_obj, "model"): |
| 56 | + return model_obj.model |
| 57 | + else: |
| 58 | + return model_obj |
| 59 | + |
| 60 | + |
| 61 | +def sparsify_model( |
| 62 | + model, |
| 63 | + sparse_cfg: str, |
| 64 | + backend=None, |
| 65 | +): |
| 66 | + """Apply sparse attention to model with optional RULER calibration. |
| 67 | +
|
| 68 | + Args: |
| 69 | + model: Model wrapper (HFLM or EvalModel) or raw model |
| 70 | + sparse_cfg: Sparse attention config name or dict |
| 71 | + backend: Backend to use (optional, overrides config backend) |
| 72 | +
|
| 73 | + Returns: |
| 74 | + The model with sparse attention applied |
| 75 | +
|
| 76 | + Note: |
| 77 | + Calibration is automatically triggered if the config contains a 'calibration' field. |
| 78 | + The calibration will auto-generate RULER dataset from the model's tokenizer. |
| 79 | + """ |
| 80 | + # Extract actual model |
| 81 | + net = _extract_model(model) |
| 82 | + |
| 83 | + # Resolve config |
| 84 | + if isinstance(sparse_cfg, str): |
| 85 | + # Try custom configs first |
| 86 | + mtsa_cfg = CUSTOM_SPARSE_CONFIG.get(sparse_cfg) |
| 87 | + if mtsa_cfg is None: |
| 88 | + # Try predefined configs |
| 89 | + mtsa_cfg = getattr(mtsa, sparse_cfg, None) |
| 90 | + if mtsa_cfg is None: |
| 91 | + raise ValueError(f"Unknown sparse_cfg: {sparse_cfg}") |
| 92 | + else: |
| 93 | + mtsa_cfg = sparse_cfg |
| 94 | + |
| 95 | + # Override backend if specified |
| 96 | + if backend: |
| 97 | + if isinstance(mtsa_cfg, dict) and "sparse_cfg" in mtsa_cfg: |
| 98 | + modified_sparse_cfg = {} |
| 99 | + for pattern, cfg in mtsa_cfg["sparse_cfg"].items(): |
| 100 | + modified_cfg = cfg.copy() if isinstance(cfg, dict) else cfg |
| 101 | + if isinstance(modified_cfg, dict): |
| 102 | + modified_cfg["backend"] = backend |
| 103 | + modified_sparse_cfg[pattern] = modified_cfg |
| 104 | + mtsa_cfg = {"sparse_cfg": modified_sparse_cfg} |
| 105 | + |
| 106 | + # Apply sparsification |
| 107 | + print(f"\nApplying sparse attention with config: {sparse_cfg}") |
| 108 | + mtsa.sparsify(net, mtsa_cfg) |
| 109 | + print("Sparse attention applied successfully!") |
| 110 | + |
| 111 | + return model |
0 commit comments