Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/transformers/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3823,6 +3823,13 @@ def set_use_kernels(self, use_kernels, kernel_config: KernelConfig | None = None

register_kernel_mapping_transformers()

# Make torch.nn.Linear kernelizable so the Hub "Linear" kernel (a tiled matmul that recomputes
# in the backward to save activation memory) is swapped in during training. nn.Linear is a
# builtin, so it is tagged via replace_kernel_forward_from_hub instead of a decorator.
from .integrations import replace_kernel_forward_from_hub

replace_kernel_forward_from_hub(nn.Linear, "Linear")

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Yep I think this is valid. My only concern is the interaction between fused tiled MLP classes - so e.g. SwiGLU doing the tiling twice ig? Would be nice if we get a proper workaround that


if kernel_config is not None:
if not isinstance(kernel_config, KernelConfig):
raise ValueError(
Expand Down Expand Up @@ -4707,6 +4714,19 @@ def detach_hidden_kernels(module):
else:
kernelize(self, device=Device(type=self.device.type), mode=mode)

# `kernelize` recurses into submodules, so a linear nested inside an already-kernelized
# non-Linear layer (e.g. a tiled MLP) gets kernelized too and is then computed twice, once by
# the parent kernel and once on its own. Restore the child's original forward; this also keeps
# PEFT adapters and hooks on it working.
for _, parent in self.named_modules():

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

cc @danieldk would it make sense to have some sort of functionality within kernels that disallows kernels on nested structures?

Imo it is a solution but not super elegant imo

if getattr(type(parent), "kernel_layer_name", None) in (None, "Linear"):
continue
for child in parent.modules():
if child is parent or getattr(type(child), "kernel_layer_name", None) != "Linear":
continue
if "forward" in vars(child):
del child.forward

self._use_kernels = True

finally:
Expand Down
18 changes: 18 additions & 0 deletions tests/kernels/test_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,24 @@ def test_setter_use_kernels(self):
self.assert_kernelized_forward_is_the_same(model, self.model_kernelized)
del model

def _assert_mlp_linears_match_baseline(self, model):
baseline = dict(self.model_not_kernelized.named_modules())
nested = [(n, m) for n, m in model.named_modules() if n.endswith((".gate_proj", ".up_proj", ".down_proj"))]
self.assertTrue(nested)
for name, module in nested:
self.assertEqual(module.forward.__code__, baseline[name].forward.__code__)

def test_nested_mlp_linears_are_not_double_kernelized(self):
# nn.Linear is tagged "Linear", so the linears inside an already-kernelized SwiGLU MLP would be
# computed twice; they must run the plain nn.Linear forward, before and after a mode switch.
model = copy.deepcopy(self.model_not_kernelized)
model.use_kernels = True
self._assert_mlp_linears_match_baseline(model)
model.train()
model.eval()
self._assert_mlp_linears_match_baseline(model)
del model

def test_unkernelize(self):
model = copy.deepcopy(self.model_kernelized)

Expand Down