|
| 1 | +# Copyright 2025 Tencent Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from .base import TransformBase |
| 16 | + |
| 17 | +__all__ = ["TransformFactory"] |
| 18 | + |
| 19 | + |
| 20 | +class _NoOpTransform(TransformBase): |
| 21 | + """No-op transform returned when slim_config has no transform_config.""" |
| 22 | + |
| 23 | + def __init__(self, quant_model, slim_config=None): |
| 24 | + # slim_config may be a dict (PTQ path), skip TransformBase.__init__ attribute assignment |
| 25 | + self.quant_model = quant_model |
| 26 | + self.config = slim_config |
| 27 | + |
| 28 | + def run(self): |
| 29 | + pass |
| 30 | + |
| 31 | + |
| 32 | +class TransformFactory: |
| 33 | + """Factory for creating TransformBase instances from config. |
| 34 | +
|
| 35 | + Usage |
| 36 | + ----- |
| 37 | + transform = TransformFactory.create(slim_model, slim_config) |
| 38 | + transform.run() |
| 39 | +
|
| 40 | + The transform name is read from ``slim_config.transform_config["name"]``, |
| 41 | + which corresponds to the ``transform.name`` field in the YAML config: |
| 42 | +
|
| 43 | + transform: |
| 44 | + name: SpinQuant |
| 45 | + spin_config: ... |
| 46 | +
|
| 47 | + Registering a new transform |
| 48 | + --------------------------- |
| 49 | + @TransformFactory.register("MyTransform") |
| 50 | + class MyTransform(TransformBase): |
| 51 | + ... |
| 52 | + """ |
| 53 | + |
| 54 | + _registry: dict[str, type[TransformBase]] = {} |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def create(cls, quant_model, slim_config) -> TransformBase: |
| 58 | + """Instantiate a transform from slim_config. |
| 59 | +
|
| 60 | + Args: |
| 61 | + quant_model: The wrapped slim model. |
| 62 | + slim_config: Config object with a ``transform_config`` dict containing ``"name"``. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + An unrun TransformBase instance. Call ``.run()`` to apply the transform. |
| 66 | +
|
| 67 | + Raises: |
| 68 | + ValueError: If transform name is missing or not registered. |
| 69 | + """ |
| 70 | + # slim_config may be a dict (PTQ path) or an object with attributes (transform path) |
| 71 | + if isinstance(slim_config, dict): |
| 72 | + transform_config = slim_config.get("transform_config") |
| 73 | + else: |
| 74 | + transform_config = getattr(slim_config, "transform_config", None) |
| 75 | + |
| 76 | + if not transform_config: |
| 77 | + return _NoOpTransform(quant_model, slim_config) |
| 78 | + |
| 79 | + name = ( |
| 80 | + transform_config.get("name") |
| 81 | + if isinstance(transform_config, dict) |
| 82 | + else getattr(transform_config, "name", None) |
| 83 | + ) |
| 84 | + if not name: |
| 85 | + return _NoOpTransform(quant_model, slim_config) |
| 86 | + |
| 87 | + if name not in cls._registry: |
| 88 | + available = list(cls._registry.keys()) |
| 89 | + raise ValueError(f"Unknown transform '{name}'. Available: {available}") |
| 90 | + |
| 91 | + return cls._registry[name](quant_model, slim_config) |
| 92 | + |
| 93 | + @classmethod |
| 94 | + def register(cls, name: str): |
| 95 | + """Decorator to register a TransformBase subclass under the given name. |
| 96 | +
|
| 97 | + Args: |
| 98 | + name: The string key used in YAML ``transform.name``. |
| 99 | +
|
| 100 | + Example: |
| 101 | + @TransformFactory.register("MyTransform") |
| 102 | + class MyTransform(TransformBase): |
| 103 | + ... |
| 104 | + """ |
| 105 | + |
| 106 | + def decorator(cls_): |
| 107 | + if not issubclass(cls_, TransformBase): |
| 108 | + raise TypeError(f"{cls_.__name__} must be a subclass of TransformBase") |
| 109 | + cls._registry[name] = cls_ |
| 110 | + return cls_ |
| 111 | + |
| 112 | + return decorator |
| 113 | + |
| 114 | + @classmethod |
| 115 | + def list_transforms(cls) -> list[str]: |
| 116 | + """Return names of all registered transforms.""" |
| 117 | + return list(cls._registry.keys()) |
0 commit comments