granite-switch 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. granite_switch-0.0.1/LICENSE +202 -0
  2. granite_switch-0.0.1/PKG-INFO +187 -0
  3. granite_switch-0.0.1/README.md +151 -0
  4. granite_switch-0.0.1/pyproject.toml +62 -0
  5. granite_switch-0.0.1/setup.cfg +4 -0
  6. granite_switch-0.0.1/src/granite_switch/__init__.py +8 -0
  7. granite_switch-0.0.1/src/granite_switch/composer/__init__.py +27 -0
  8. granite_switch-0.0.1/src/granite_switch/composer/adapter_discovery.py +324 -0
  9. granite_switch-0.0.1/src/granite_switch/composer/adapter_loader.py +467 -0
  10. granite_switch-0.0.1/src/granite_switch/composer/arch.py +401 -0
  11. granite_switch-0.0.1/src/granite_switch/composer/compose_granite_switch.py +948 -0
  12. granite_switch-0.0.1/src/granite_switch/composer/compose_utils.py +231 -0
  13. granite_switch-0.0.1/src/granite_switch/composer/reporting/__init__.py +20 -0
  14. granite_switch-0.0.1/src/granite_switch/composer/reporting/adapter_analysis.py +106 -0
  15. granite_switch-0.0.1/src/granite_switch/composer/reporting/compose_report.py +402 -0
  16. granite_switch-0.0.1/src/granite_switch/composer/reporting/hiding_constant_report.py +58 -0
  17. granite_switch-0.0.1/src/granite_switch/composer/reporting/model_card.py +436 -0
  18. granite_switch-0.0.1/src/granite_switch/composer/reporting/population_table.py +194 -0
  19. granite_switch-0.0.1/src/granite_switch/composer/tokenizer_setup.py +338 -0
  20. granite_switch-0.0.1/src/granite_switch/composer/validator.py +186 -0
  21. granite_switch-0.0.1/src/granite_switch/composer/weight_remapper.py +137 -0
  22. granite_switch-0.0.1/src/granite_switch/composer/weight_transfer.py +669 -0
  23. granite_switch-0.0.1/src/granite_switch/config.py +290 -0
  24. granite_switch-0.0.1/src/granite_switch/hf/__init__.py +21 -0
  25. granite_switch-0.0.1/src/granite_switch/hf/core/__init__.py +14 -0
  26. granite_switch-0.0.1/src/granite_switch/hf/core/lora.py +671 -0
  27. granite_switch-0.0.1/src/granite_switch/hf/modeling_granite_switch.py +502 -0
  28. granite_switch-0.0.1/src/granite_switch/hf/switch/__init__.py +31 -0
  29. granite_switch-0.0.1/src/granite_switch/hf/switch/single.py +198 -0
  30. granite_switch-0.0.1/src/granite_switch/vllm/__init__.py +101 -0
  31. granite_switch-0.0.1/src/granite_switch/vllm/core/__init__.py +23 -0
  32. granite_switch-0.0.1/src/granite_switch/vllm/core/decoder.py +415 -0
  33. granite_switch-0.0.1/src/granite_switch/vllm/core/lora.py +345 -0
  34. granite_switch-0.0.1/src/granite_switch/vllm/core/lora_kernel_meta.py +465 -0
  35. granite_switch-0.0.1/src/granite_switch/vllm/granite_switch_model.py +694 -0
  36. granite_switch-0.0.1/src/granite_switch/vllm/switch/__init__.py +31 -0
  37. granite_switch-0.0.1/src/granite_switch/vllm/switch/single.py +169 -0
  38. granite_switch-0.0.1/src/granite_switch.egg-info/PKG-INFO +187 -0
  39. granite_switch-0.0.1/src/granite_switch.egg-info/SOURCES.txt +41 -0
  40. granite_switch-0.0.1/src/granite_switch.egg-info/dependency_links.txt +1 -0
  41. granite_switch-0.0.1/src/granite_switch.egg-info/entry_points.txt +2 -0
  42. granite_switch-0.0.1/src/granite_switch.egg-info/requires.txt +34 -0
  43. granite_switch-0.0.1/src/granite_switch.egg-info/top_level.txt +1 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: granite-switch
3
+ Version: 0.0.1
4
+ Summary: Granite Switch: Embedded LoRA adapter switching for Granite models
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: <3.14,>=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: torch>=2.0.0
10
+ Requires-Dist: transformers>=5.5.1
11
+ Provides-Extra: hf
12
+ Requires-Dist: accelerate>=0.20.0; extra == "hf"
13
+ Provides-Extra: vllm
14
+ Requires-Dist: vllm<0.20.0,>=0.19.1; extra == "vllm"
15
+ Provides-Extra: vllm20
16
+ Requires-Dist: vllm<0.21.0,>=0.20.0; extra == "vllm20"
17
+ Provides-Extra: compose
18
+ Requires-Dist: huggingface_hub; extra == "compose"
19
+ Requires-Dist: pyyaml; extra == "compose"
20
+ Requires-Dist: tqdm; extra == "compose"
21
+ Requires-Dist: safetensors; extra == "compose"
22
+ Provides-Extra: build
23
+ Requires-Dist: huggingface_hub; extra == "build"
24
+ Requires-Dist: pyyaml; extra == "build"
25
+ Requires-Dist: tqdm; extra == "build"
26
+ Requires-Dist: safetensors; extra == "build"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest; extra == "dev"
29
+ Requires-Dist: granite-switch[compose,hf,vllm]; extra == "dev"
30
+ Provides-Extra: dev-vllm20
31
+ Requires-Dist: pytest; extra == "dev-vllm20"
32
+ Requires-Dist: granite-switch[compose,hf,vllm20]; extra == "dev-vllm20"
33
+ Provides-Extra: test
34
+ Requires-Dist: pytest; extra == "test"
35
+ Dynamic: license-file
36
+
37
+ # Granite Switch — Fine-tuning, finally composable
38
+
39
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
40
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
41
+
42
+ | [**Browse Adapters**](https://huggingface.co/collections/ibm-granite/granite-libraries) | [Models on HF](https://huggingface.co/ibm-granite/granite-switch-4.1-8b-preview) | [Tutorials](tutorials/README.md) |
43
+
44
+ Task-specific fine-tuning delivers large accuracy gains on small models — but shipping a separate model per task is operationally painful. Granite Switch gives you the accuracy of many models with the footprint of one: compose a single checkpoint from our adapter library in minutes, then swap or upgrade individual capabilities as your needs change.
45
+
46
+ Browse the full set of ready-to-use adapters in the [Granite Libraries collection](https://huggingface.co/collections/ibm-granite/granite-libraries) on Hugging Face.
47
+
48
+ ## Key Features
49
+
50
+ - **Composable** — Combine independently trained adapters into one checkpoint, whether IBM's or yours. Swap, upgrade, or customize without retraining.
51
+ - **Fast** — Built on IBM's Activated LoRA technology for efficient KV cache reuse, low latency, and high inference throughput.
52
+ - **Accurate** — Task-specific adapters can match and even surpass the accuracy of significantly larger generalist models, while requiring only a fraction of the serving cost. See the [adapter catalog](https://generative-computing.github.io/granite-switch/adapter_catalog.html#hallucination-detection) for benchmark comparisons across all 12 adapters.
53
+ - **Inference-ready** — Support for Hugging Face and vLLM.
54
+
55
+ ## Quick Start
56
+
57
+ ### Install
58
+
59
+ ```bash
60
+ git clone https://github.com/generative-computing/granite-switch.git
61
+ cd granite-switch
62
+ python -m venv venv && source venv/bin/activate
63
+
64
+ # Pick what you need:
65
+ pip install -e ".[compose]" # Compose modular models
66
+ pip install -e ".[hf]" # HuggingFace inference
67
+ pip install -e ".[vllm]" # vLLM production inference (0.19.x)
68
+ pip install -e ".[vllm20]" # vLLM 0.20+ (requires CUDA 13+)
69
+ pip install -e ".[dev]" # Everything (uses vLLM 0.19.x by default)
70
+ pip install -e ".[dev-vllm20]" # Dev environment with vLLM 0.20+
71
+ ```
72
+
73
+ Requires Python 3.9+ and PyTorch 2.0+.
74
+
75
+ > **vLLM version note:** This project currently defaults to vLLM 0.19.1 due to vLLM 0.20's
76
+ > dependency on CUDA 13.0+ (via PyTorch 2.11), which is incompatible with many existing
77
+ > environments running CUDA 12.x drivers. Use `.[vllm20]` if your environment supports CUDA 13+.
78
+
79
+ ### Compose a Model
80
+
81
+ Combine a base Granite model with adapters into a single deployable checkpoint:
82
+
83
+ ```bash
84
+ python -m granite_switch.composer.compose_granite_switch \
85
+ --base-model ibm-granite/granite-4.1-3b \
86
+ --adapters ibm-granite/granitelib-core-r1.0 ibm-granite/granitelib-rag-r1.0 ibm-granite/granitelib-guardian-r1.0 \
87
+ --output ./my-model
88
+ ```
89
+
90
+ Use the **[Adapter Composer](https://generative-computing.github.io/granite-switch/adapter_catalog.html)** to browse available adapters, compare benchmarks, and generate a ready-to-run compose command.
91
+
92
+ This downloads the base model, embeds compatible LoRA adapters (with a preference towards activated LoRA), adds control tokens and a chat template, and produces a model directory that works with both HuggingFace and vLLM.
93
+
94
+ For convenience, you can find already composed Granite Switch models for the Granite 4.1 model family here:
95
+
96
+ - [ibm-granite/granite-switch-4.1-3b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-3b-preview)
97
+ - [ibm-granite/granite-switch-4.1-8b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-8b-preview)
98
+ - [ibm-granite/granite-switch-4.1-30b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-30b-preview)
99
+
100
+
101
+ ### Run Inference
102
+
103
+ **vLLM + Mellea (recommended):**
104
+
105
+ ```bash
106
+ pip install mellea
107
+ python -m vllm.entrypoints.openai.api_server --model ./my-model --port 8000
108
+ ```
109
+
110
+ ```python
111
+ from mellea.backends.openai import OpenAIBackend
112
+ from mellea.stdlib.components.intrinsic import rag
113
+ from mellea.stdlib.context import ChatContext
114
+
115
+ backend = OpenAIBackend(
116
+ model_id="./my-model",
117
+ base_url="http://localhost:8000/v1",
118
+ api_key="unused",
119
+ )
120
+ backend.register_embedded_adapter_model("./my-model")
121
+
122
+ query = "I want to ask you something. what is...mmmm the the main city(capital you call it,right?) of France?"
123
+ ctx = ChatContext()
124
+
125
+ rewritten = rag.rewrite_question(query, ctx, backend)
126
+ print(f"original: {query}")
127
+ print(f"rewritten: {rewritten}")
128
+ # => "What is the capital of France?"
129
+ ```
130
+
131
+ **HuggingFace:**
132
+
133
+ ```python
134
+ import granite_switch.hf # Register HF backend
135
+
136
+ from transformers import AutoModelForCausalLM, AutoTokenizer
137
+
138
+ model = AutoModelForCausalLM.from_pretrained("./my-model", device_map="auto")
139
+ tokenizer = AutoTokenizer.from_pretrained("./my-model")
140
+
141
+ messages = [{"role": "user", "content": "What is the capital of France?"}]
142
+ documents = [{"doc_id": "1", "text": "Paris is the capital of France."}]
143
+
144
+ prompt = tokenizer.apply_chat_template(
145
+ messages,
146
+ documents=documents,
147
+ adapter_name="answerability", # activates the answerability adapter
148
+ add_generation_prompt=True,
149
+ tokenize=False,
150
+ )
151
+ outputs = model.generate(**tokenizer(prompt, return_tensors="pt").to(model.device))
152
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
153
+ # => "answerable"
154
+ ```
155
+
156
+ ## How It Works
157
+
158
+ Granite Switch uses a **switch layer**—a small attention-based mechanism that reads control tokens from the input and determines which adapter's LoRA weights to apply at each position.
159
+
160
+ **What makes composition work:**
161
+
162
+ - **KV cache normalization** — each adapter sees only the base model's KV cache, never another adapter's internal state
163
+ - **No joint training required** — Adapters can be developed, tested, and published independently
164
+ - **Standard inference** — The entire model loads in vLLM with zero code changes
165
+
166
+ ## Documentation
167
+
168
+ For detailed tutorials and many working examples, see the [Tutorials](tutorials/README.md) section.
169
+
170
+ ## Citation
171
+
172
+ ```bibtex
173
+ @software{granite_switch,
174
+ title = {Granite Switch: Coarse-Grained Expert Switching for LLMs},
175
+ author = {IBM Research},
176
+ year = {2025},
177
+ url = {https://github.com/ibm-granite/granite-switch}
178
+ }
179
+ ```
180
+
181
+ ## IBM ❤️ Open Source AI
182
+
183
+ Granite Switch was started by IBM Research.
184
+
185
+ ## License
186
+
187
+ Granite Switch has an Apache-2.0 license, as found in the [LICENSE](LICENSE) file.
@@ -0,0 +1,151 @@
1
+ # Granite Switch — Fine-tuning, finally composable
2
+
3
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
4
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
5
+
6
+ | [**Browse Adapters**](https://huggingface.co/collections/ibm-granite/granite-libraries) | [Models on HF](https://huggingface.co/ibm-granite/granite-switch-4.1-8b-preview) | [Tutorials](tutorials/README.md) |
7
+
8
+ Task-specific fine-tuning delivers large accuracy gains on small models — but shipping a separate model per task is operationally painful. Granite Switch gives you the accuracy of many models with the footprint of one: compose a single checkpoint from our adapter library in minutes, then swap or upgrade individual capabilities as your needs change.
9
+
10
+ Browse the full set of ready-to-use adapters in the [Granite Libraries collection](https://huggingface.co/collections/ibm-granite/granite-libraries) on Hugging Face.
11
+
12
+ ## Key Features
13
+
14
+ - **Composable** — Combine independently trained adapters into one checkpoint, whether IBM's or yours. Swap, upgrade, or customize without retraining.
15
+ - **Fast** — Built on IBM's Activated LoRA technology for efficient KV cache reuse, low latency, and high inference throughput.
16
+ - **Accurate** — Task-specific adapters can match and even surpass the accuracy of significantly larger generalist models, while requiring only a fraction of the serving cost. See the [adapter catalog](https://generative-computing.github.io/granite-switch/adapter_catalog.html#hallucination-detection) for benchmark comparisons across all 12 adapters.
17
+ - **Inference-ready** — Support for Hugging Face and vLLM.
18
+
19
+ ## Quick Start
20
+
21
+ ### Install
22
+
23
+ ```bash
24
+ git clone https://github.com/generative-computing/granite-switch.git
25
+ cd granite-switch
26
+ python -m venv venv && source venv/bin/activate
27
+
28
+ # Pick what you need:
29
+ pip install -e ".[compose]" # Compose modular models
30
+ pip install -e ".[hf]" # HuggingFace inference
31
+ pip install -e ".[vllm]" # vLLM production inference (0.19.x)
32
+ pip install -e ".[vllm20]" # vLLM 0.20+ (requires CUDA 13+)
33
+ pip install -e ".[dev]" # Everything (uses vLLM 0.19.x by default)
34
+ pip install -e ".[dev-vllm20]" # Dev environment with vLLM 0.20+
35
+ ```
36
+
37
+ Requires Python 3.9+ and PyTorch 2.0+.
38
+
39
+ > **vLLM version note:** This project currently defaults to vLLM 0.19.1 due to vLLM 0.20's
40
+ > dependency on CUDA 13.0+ (via PyTorch 2.11), which is incompatible with many existing
41
+ > environments running CUDA 12.x drivers. Use `.[vllm20]` if your environment supports CUDA 13+.
42
+
43
+ ### Compose a Model
44
+
45
+ Combine a base Granite model with adapters into a single deployable checkpoint:
46
+
47
+ ```bash
48
+ python -m granite_switch.composer.compose_granite_switch \
49
+ --base-model ibm-granite/granite-4.1-3b \
50
+ --adapters ibm-granite/granitelib-core-r1.0 ibm-granite/granitelib-rag-r1.0 ibm-granite/granitelib-guardian-r1.0 \
51
+ --output ./my-model
52
+ ```
53
+
54
+ Use the **[Adapter Composer](https://generative-computing.github.io/granite-switch/adapter_catalog.html)** to browse available adapters, compare benchmarks, and generate a ready-to-run compose command.
55
+
56
+ This downloads the base model, embeds compatible LoRA adapters (with a preference towards activated LoRA), adds control tokens and a chat template, and produces a model directory that works with both HuggingFace and vLLM.
57
+
58
+ For convenience, you can find already composed Granite Switch models for the Granite 4.1 model family here:
59
+
60
+ - [ibm-granite/granite-switch-4.1-3b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-3b-preview)
61
+ - [ibm-granite/granite-switch-4.1-8b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-8b-preview)
62
+ - [ibm-granite/granite-switch-4.1-30b-preview](https://huggingface.co/ibm-granite/granite-switch-4.1-30b-preview)
63
+
64
+
65
+ ### Run Inference
66
+
67
+ **vLLM + Mellea (recommended):**
68
+
69
+ ```bash
70
+ pip install mellea
71
+ python -m vllm.entrypoints.openai.api_server --model ./my-model --port 8000
72
+ ```
73
+
74
+ ```python
75
+ from mellea.backends.openai import OpenAIBackend
76
+ from mellea.stdlib.components.intrinsic import rag
77
+ from mellea.stdlib.context import ChatContext
78
+
79
+ backend = OpenAIBackend(
80
+ model_id="./my-model",
81
+ base_url="http://localhost:8000/v1",
82
+ api_key="unused",
83
+ )
84
+ backend.register_embedded_adapter_model("./my-model")
85
+
86
+ query = "I want to ask you something. what is...mmmm the the main city(capital you call it,right?) of France?"
87
+ ctx = ChatContext()
88
+
89
+ rewritten = rag.rewrite_question(query, ctx, backend)
90
+ print(f"original: {query}")
91
+ print(f"rewritten: {rewritten}")
92
+ # => "What is the capital of France?"
93
+ ```
94
+
95
+ **HuggingFace:**
96
+
97
+ ```python
98
+ import granite_switch.hf # Register HF backend
99
+
100
+ from transformers import AutoModelForCausalLM, AutoTokenizer
101
+
102
+ model = AutoModelForCausalLM.from_pretrained("./my-model", device_map="auto")
103
+ tokenizer = AutoTokenizer.from_pretrained("./my-model")
104
+
105
+ messages = [{"role": "user", "content": "What is the capital of France?"}]
106
+ documents = [{"doc_id": "1", "text": "Paris is the capital of France."}]
107
+
108
+ prompt = tokenizer.apply_chat_template(
109
+ messages,
110
+ documents=documents,
111
+ adapter_name="answerability", # activates the answerability adapter
112
+ add_generation_prompt=True,
113
+ tokenize=False,
114
+ )
115
+ outputs = model.generate(**tokenizer(prompt, return_tensors="pt").to(model.device))
116
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
117
+ # => "answerable"
118
+ ```
119
+
120
+ ## How It Works
121
+
122
+ Granite Switch uses a **switch layer**—a small attention-based mechanism that reads control tokens from the input and determines which adapter's LoRA weights to apply at each position.
123
+
124
+ **What makes composition work:**
125
+
126
+ - **KV cache normalization** — each adapter sees only the base model's KV cache, never another adapter's internal state
127
+ - **No joint training required** — Adapters can be developed, tested, and published independently
128
+ - **Standard inference** — The entire model loads in vLLM with zero code changes
129
+
130
+ ## Documentation
131
+
132
+ For detailed tutorials and many working examples, see the [Tutorials](tutorials/README.md) section.
133
+
134
+ ## Citation
135
+
136
+ ```bibtex
137
+ @software{granite_switch,
138
+ title = {Granite Switch: Coarse-Grained Expert Switching for LLMs},
139
+ author = {IBM Research},
140
+ year = {2025},
141
+ url = {https://github.com/ibm-granite/granite-switch}
142
+ }
143
+ ```
144
+
145
+ ## IBM ❤️ Open Source AI
146
+
147
+ Granite Switch was started by IBM Research.
148
+
149
+ ## License
150
+
151
+ Granite Switch has an Apache-2.0 license, as found in the [LICENSE](LICENSE) file.
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "granite-switch"
7
+ version = "0.0.1"
8
+ description = "Granite Switch: Embedded LoRA adapter switching for Granite models"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10,<3.14"
12
+ dependencies = [
13
+ "torch>=2.0.0",
14
+ "transformers>=5.5.1",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ hf = ["accelerate>=0.20.0"]
19
+ vllm = ["vllm>=0.19.1,<0.20.0"]
20
+ vllm20 = ["vllm>=0.20.0,<0.21.0"]
21
+ compose = ["huggingface_hub", "pyyaml", "tqdm", "safetensors"]
22
+ build = ["huggingface_hub", "pyyaml", "tqdm", "safetensors"] # Backward compatibility alias for compose
23
+ dev = ["pytest", "granite-switch[hf,vllm,compose]"]
24
+ dev-vllm20 = ["pytest", "granite-switch[hf,vllm20,compose]"]
25
+ test = ["pytest"]
26
+
27
+ [project.entry-points."vllm.general_plugins"]
28
+ register_granite_switch = "granite_switch.vllm:register"
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
32
+ addopts = ["--ignore=tests/_legacy", "-m", "not deep"]
33
+ markers = [
34
+ "gpu: requires CUDA GPU",
35
+ "vllm: requires vLLM installed",
36
+ "slow: takes > 30s",
37
+ "deep: expensive code-theory tests (m=8 / 256-dim); run with: pytest -m deep",
38
+ "requires_model: needs a real model checkpoint",
39
+ ]
40
+
41
+ [tool.uv]
42
+ conflicts = [
43
+ [
44
+ { extra = "vllm" },
45
+ { extra = "vllm20" },
46
+ ],
47
+ [
48
+ { extra = "dev" },
49
+ { extra = "vllm20" },
50
+ ],
51
+ [
52
+ { extra = "dev" },
53
+ { extra = "dev-vllm20" },
54
+ ],
55
+ [
56
+ { extra = "dev-vllm20" },
57
+ { extra = "vllm" },
58
+ ],
59
+ ]
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Granite Switch: Embedded LoRA adapter switching for Granite models."""
3
+
4
+ __version__ = "0.1.0"
5
+
6
+ from .config import GraniteSwitchConfig
7
+
8
+ __all__ = ["GraniteSwitchConfig", "__version__"]
@@ -0,0 +1,27 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Compose utilities for Granite Switch models.
3
+
4
+ This module provides utilities for composing Granite Switch checkpoints from
5
+ base models and LoRA adapters.
6
+ """
7
+
8
+ from .weight_remapper import AdapterRemapper, RemapResult
9
+ from .compose_utils import GraniteSwitchComposer
10
+ from .arch import (
11
+ ArchDescriptor,
12
+ ModuleDescriptor,
13
+ resolve_arch,
14
+ granite_dense_arch,
15
+ granite_moe_hybrid_arch,
16
+ )
17
+
18
+ __all__ = [
19
+ "AdapterRemapper",
20
+ "RemapResult",
21
+ "GraniteSwitchComposer",
22
+ "ArchDescriptor",
23
+ "ModuleDescriptor",
24
+ "resolve_arch",
25
+ "granite_dense_arch",
26
+ "granite_moe_hybrid_arch",
27
+ ]