Repository: huggingface/transformers
Pull request: allow registration of custom checkpoint conversion mappings

# What does this PR do?

For custom modeling, this provides a clean route to adding new or overwriting existing mappings with custom mappings. Additionally, it properly memoizes the cached mappings.

## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?
@ArthurZucker 
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Changed files:
filename: src/transformers/conversion_mapping.py
patch: @@ -186,10 +186,22 @@ def _build_checkpoint_conversion_mapping():
 
 def get_checkpoint_conversion_mapping(model_type):
     global _checkpoint_conversion_mapping_cache
-    _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping()
+    if _checkpoint_conversion_mapping_cache is None:
+        _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping()
     return deepcopy(_checkpoint_conversion_mapping_cache.get(model_type))
 
 
+def register_checkpoint_conversion_mapping(
+    model_type: str, mapping: list[WeightConverter | WeightRenaming], overwrite: bool = False
+) -> None:
+    global _checkpoint_conversion_mapping_cache
+    if _checkpoint_conversion_mapping_cache is None:
+        _checkpoint_conversion_mapping_cache = _build_checkpoint_conversion_mapping()
+    if model_type in _checkpoint_conversion_mapping_cache and not overwrite:
+        raise ValueError(f"Model type {model_type} already exists in the checkpoint conversion mapping.")
+    _checkpoint_conversion_mapping_cache[model_type] = mapping
+
+
 # DO NOT MODIFY, KEPT FOR BC ONLY
 VLMS = [
     "aria",

filename: tests/utils/test_core_model_loading.py
patch: @@ -18,6 +18,7 @@
 import torch.nn as nn
 
 from transformers import PretrainedConfig
+from transformers.conversion_mapping import get_checkpoint_conversion_mapping, register_checkpoint_conversion_mapping
 from transformers.core_model_loading import (
     Chunk,
     Concatenate,
@@ -505,5 +506,43 @@ def __init__(self):
         torch.testing.assert_close(dequantized_q, expected_q, rtol=1e-2, atol=1e-2)
 
 
+class TestConversionMapping(unittest.TestCase):
+    def test_register_checkpoint_conversion_mapping(self):
+        register_checkpoint_conversion_mapping(
+            "foobar",
+            [
+                WeightRenaming(".block_sparse_moe.gate", ".mlp.gate"),
+            ],
+        )
+        self.assertEqual(len(get_checkpoint_conversion_mapping("foobar")), 1)
+
+    def test_register_checkpoint_conversion_mapping_overwrites(self):
+        register_checkpoint_conversion_mapping(
+            "foobarbaz",
+            [
+                WeightRenaming(".block_sparse_moe.gate", ".mlp.gate"),
+            ],
+        )
+        with self.assertRaises(ValueError):
+            register_checkpoint_conversion_mapping(
+                "foobarbaz",
+                [
+                    WeightRenaming(".block_sparse_moe.foo", ".mlp.foo"),
+                    WeightRenaming(".block_sparse_moe.bar", ".mlp.bar"),
+                ],
+            )
+
+        register_checkpoint_conversion_mapping(
+            "foobarbaz",
+            [
+                WeightRenaming(".block_sparse_moe.foo", ".mlp.foo"),
+                WeightRenaming(".block_sparse_moe.bar", ".mlp.bar"),
+            ],
+            overwrite=True,
+        )
+
+        self.assertEqual(len(get_checkpoint_conversion_mapping("foobarbaz")), 2)
+
+
 if __name__ == "__main__":
     unittest.main()