Skip to content

[Module] Add configurable Embedding with init_weights support - #2428

Merged
fegin merged 19 commits into
mainfrom
gh/fegin/81/head
Mar 5, 2026
Merged

fegin merged 19 commits into
mainfrom
gh/fegin/81/head

Conversation

@fegin

@fegin fegin commented Feb 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Why the Change
This is the first step to make all submodules configurable and inherit from Module. We will further extend Module to support per-module sharding configurations.

Summary

  • Introduce Embedding(nn.Embedding, Module) in torchtitan/models/common/embedding.py — a configurable embedding that uses diamond inheritance to reuse nn.Embedding logic while satisfying the Module protocol (init_weights + Configurable.Config.build()).

  • Replace raw nn.Embedding(vocab_size, dim) construction in Decoder with config.tok_embeddings.build(), making the token embedding configurable (e.g., custom init_mean/init_std) without changing any model subclass.

  • Harden Module.init_weights with raise NotImplementedError for runtime enforcement, since abstractmethod alone is insufficient (nn.Module uses type, not ABCMeta).

  • Add unit tests for the Module diamond inheritance pattern and Embedding config/build lifecycle.

[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Feb 24, 2026
**Why the Change**
This is the first step to make all submodules configurable and inherit from Module. We will further extend Module to support per-module sharding configurations.

**Summary**

- Introduce NNEmbedding(nn.Embedding, Module) in torchtitan/models/common/embedding.py — a configurable embedding that uses diamond inheritance to reuse
nn.Embedding logic while satisfying the Module protocol (init_weights + Configurable.Config.build()).

- Replace raw nn.Embedding(vocab_size, dim) construction in Decoder with config.tok_embeddings.build(), making the token embedding configurable (e.g., custom
init_mean/init_std) without changing any model subclass.

- Harden Module.init_weights with raise NotImplementedError for runtime enforcement, since abstractmethod alone is insufficient (nn.Module uses type, not
ABCMeta).

- Add unit tests for the Module diamond inheritance pattern and NNEmbedding config/build lifecycle.


ghstack-source-id: 8c4acde
Pull-Request: #2428
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Feb 24, 2026
@fegin
fegin marked this pull request as draft February 24, 2026 06:13
Comment thread torchtitan/models/common/embedding.py Resolved
Comment thread torchtitan/models/common/embedding.py Resolved
@@ -20,5 +20,15 @@ class Module(nn.Module, Configurable):

@abstractmethod
def init_weights(self, **kwargs) -> None:

ghost Feb 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should put this in config, instead of in module, because what I mentioned in the refactor PR summary #2386:

Refactor init_weights into Module.Config instead of staying in Module
The benefit is that param init can be configurable; o/w we are coupling module implementation and its weight init.
This may require refactor of current TransformerBlock and its config. E.g. weight_init_std may need to be put in config, with post_init determining its value. (See related complaints / discussions on post_init by chz)

ghost Feb 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also would love to have a better name.
Previous this was called init_weights to be different from reset_parameters, but weights is a too narrow term. FSDP1 called param_init_fn (see https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md); internal called it param_init.

ghost Feb 24, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer init_states as we also initialize buffers such as freqs_cis. As for moving into config, I prefer to do that after I modify all the three modules (Embedding, RMSNorm and Linear) to Module.

ghost Feb 27, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it be cleaner to make a new object 'ModuleInitializer' and then use config to choose which ModuleInitializer to use for a Module? It feels a little weird to me to put actual model init logic into a Config class directly.

ghost Feb 27, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess a question would be -- is it possible to create infinite ways of initialization with a finite set of ModuleInitializer configs.

[ghstack-poisoned]
@fegin fegin changed the title [Module] Add configurable NNEmbedding with init_weights support [Module] Add configurable Embedding with init_weights support Feb 24, 2026
Comment thread torchtitan/models/common/decoder.py Resolved
Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +77 to +81
def __post_init__(self):
# NOTE: If subclasses override __post_init__, they MUST call
# super().__post_init__() to ensure tok_embeddings is configured.
self.tok_embeddings.num_embeddings = self.vocab_size
self.tok_embeddings.embedding_dim = self.dim

ghost Feb 24, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be tricky, e.g. https://github.com/openai/chz/blob/main/docs/21_post_init.md

I'd like to further discuss how fields in a submodule should be set by parent module. cc @shuhuayu

ghost Feb 24, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decided to use kwargs as I found some issues in a later PR.

ghost Feb 26, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be tricky, e.g. https://github.com/openai/chz/blob/main/docs/21_post_init.md

I'd like to further discuss how fields in a submodule should be set by parent module. cc @shuhuayu

Nice reference. I think the current style is lean in that parent modules use build function to pass shared fields to the submodule, and no need to duplicate them on the submodules. I see this is consistent across several modules.

Do you think it is useful to add an utility to print all configs so people can inspect the config trees conveniently? Sometimes people may get some undesired default values silently.

ghost Feb 26, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ghost Feb 26, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it only prints training configs. I was thinking model configs, which is printed by default. In this pr, token embedding has configurable init parameters so they will be printed, but for other modules, they do not.

ghost Feb 26, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

trainer config contains model config
all modules should have init params in config, that's a refactor to be done. Actually I'm not sure how serializable it can be.

[ghstack-poisoned]
[ghstack-poisoned]
Chien-Chin Huang added 2 commits February 26, 2026 13:37
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin requested review from shuhuayu and tianyu-l February 26, 2026 22:53
@fegin
fegin marked this pull request as ready for review February 26, 2026 22:55
@fegin
fegin requested review from wconstab and wwwjn as code owners February 26, 2026 22:55

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good in general

Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/config/configurable.py Outdated
)
return self._owner(config=self, **kwargs)
if not kwargs:
return self._owner(config=replace(self))

ghost Feb 27, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh nice, does replace creates a clone? shallow or deep?

ghost Feb 27, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, a new dataclass. Shallow.

Comment thread torchtitan/models/common/decoder.py Resolved
Comment thread torchtitan/models/common/embedding.py Resolved
Comment thread torchtitan/models/common/embedding.py Outdated
Comment on lines +33 to +34
num_embeddings: int | None = None
embedding_dim: int | None = None

ghost Feb 27, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you tell me default None is unsafe?

What if we don't set default, e.g.

Suggested change
num_embeddings: int | None = None
embedding_dim: int | None = None
num_embeddings: int
embedding_dim: int

ghost Feb 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uh, yes, this is the part I feel it is not perfect but also there is no perfect way to do. So If we don't have the default, then users always have to specify these values even though num_embeddings and embedding_dim will also be passed from build().

None is not safe 1) Python docs mention None is not safe because None may be a legit value for some dataclass field so Python introduces MISSING but this is minor for our case. 2) None is not safe in that all future Module developers need to remember to set the default values of shared fields as None.

Having default will give users the flexibility to NOT specify the values but also at some points they can do it. For example, a Module can have some fields that may or may not always share values with other components. Embedding is not the case so we can remove None. However if we decide to offer the flexibility, we have to keep the rule strict and simple, all fields that share values with others must set the default value as None. So Embedding should also define None.

An alternative is that users always need to set the values explicitly even though they are going to be passed from build() as well. IMO, this is also okay as our config is a python script, it is easy to share some variables in the config.

Either way works. We just need to have a consensus which one to do.

Chien-Chin Huang added 2 commits February 27, 2026 17:30
[ghstack-poisoned]
[ghstack-poisoned]
@fegin

ghost commented Feb 28, 2026

Copy link
Copy Markdown
Contributor Author

Now the fields that share values among components will use field(init=False).

Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/config/configurable.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants