Improve module name handling for local custom code
Author: XuehaiPan
Pull request: yes

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

This is a follow-up for PR #40745.

- #40745

Fixes #40496


## 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?
- [X] 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.
- [X] 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?

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.

@Rocketknight1

<!-- 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
- vision models: @amyeroberts, @qubvel
- speech models: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface, @SunMarc and @qgallouedec
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
> Using lots of `_dot_` and `_hyphen_` seems very confusing, though - maybe we can just replace `-` and `.` with `_`, and prepend `_` if it starts with a digit?

Replacing punctuations with only one character (`_`) may have a very high risk of module name collision. Underline `_` is very commonly used. Once a module is imported, the module object will be cached in `sys.modules`.

Alright, makes sense. Last question, though: I know that using `.` caused a bug because it was mistaken as an import separator, but do we still get the same bug with `-` without this PR?

> Alright, makes sense. Last question, though: I know that using `.` caused a bug because it was mistaken as an import separator, but do we still get the same bug with `-` without this PR?

String with `-` is not a valid Python identifier, which cannot be used as a module name. ~It will raise `SyntaxError` without this PR.~ (The parent dirname does not break relative imports.) For dot `.`, the previous PR has fixed the `ImportError`.

Hmm, if `-` in the dirname doesn't break relative imports, do we still need to replace it with `hyphen`?

> Hmm, if `-` in the dirname doesn't break relative imports, do we still need to replace it with `hyphen`?

@Rocketknight1 I can confirm that the custom code for model name `123-saved-model-v1.0` works fine with/without this PR.

Without this PR:

```console
$ git clone https://github.com/zachmoshe/transformers-dotted-models-example
$ cd transformers-dotted-models-example
$ sed -i '' -E 's|saved_model_v1.0|123-saved-model-v1.0|g' load.py
$ sed -i '' -E 's|saved_model_v1.0|123-saved-model-v1.0|g' save.py
$ rm -rf ~/.cache/huggingface/modules
$ python3 save.py
MyModel(
  (linear): Linear(in_features=256, out_features=1, bias=True)
)
model saved.
tensor([[66.3642]], grad_fn=<AddmmBackward0>)
$ python3 load.py
MyModel(
  (linear): Linear(in_features=256, out_features=1, bias=True)
)
tensor([[66.3642]], grad_fn=<AddmmBackward0>)
$ ls ~/.cache/huggingface/modules/transformers_modules
__init__.py              __pycache__              123-saved-model-v1_dot_0
```

With this PR:

```console
$ rm -rf ~/.cache/huggingface/modules
$ rm -rf ./123-saved-model-v1.0
$ python3 save.py
MyModel(
  (linear): Linear(in_features=256, out_features=1, bias=True)
)
model saved.
tensor([[69.8205]], grad_fn=<AddmmBackward0>)
$ python3 load.py
MyModel(
  (linear): Linear(in_features=256, out_features=1, bias=True)
)
tensor([[69.8205]], grad_fn=<AddmmBackward0>)
$ ls ~/.cache/huggingface/modules/transformers_modules
__init__.py     __pycache__     _123_hyphen_saved_hyphen_model_hyphen_v1_dot_0
```

------

The point is to make all sub-directories in `~/.cache/huggingface/modules` a valid Python subpackage (with a valid dirname as Python identifier). Because there is a `__init__.py` file in `~/.cache/huggingface/modules` and `transformers_modules`, they are Python subpackages.

> removing `!r` because `name` and `new_name` are already strings

I intentionally use `!r` to add quotes for the string names. I'm fine with either `!r` (using `repr`) or `!s` (using `str`).

```python
name = 'my-model-1.5b'
print('Model {name} has 1.5B parameters.')
# -> Model my-model-1.5b has 1.5B parameters.
print('Model {name!r} has 1.5B parameters.')
# -> Model 'my-model-1.5b' has 1.5B parameters.
```

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_40809). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@XuehaiPan @Rocketknight1 

It looks like this PR makes it emit warnings when using not a custom model but a model from the Hugging Face Hub.

I'm using the most recent commit on main: f22cb1e8689905091acb07e238b670aadde1e4ee

```py
from transformers import AutoModelForCausalLM

checkpoint = "HuggingFaceTB/SmolLM-135M"
model = AutoModelForCausalLM.from_pretrained(checkpoint)
```

```sh
python3 test.py
```

```sh
The module name HuggingFaceTB/SmolLM_hyphen_135M (originally HuggingFaceTB/SmolLM-135M) is not a valid Python identifier. Please rename the original module to avoid import issues.
```

Is this expected behavior? For me, it's unexpected because I cannot rename the original module for `"HuggingFaceTB/SmolLM-135M"`.

> Is this expected behavior?

@st81 Thanks for raising this. It is not an expected behavior. I opened a PR to resolve this:

- #41243