Skip to content

Disable kernels before wrapping a model in nn.DataParallel - #51239

Closed
SunMarc wants to merge 1 commit into
mainfrom
disable-kernels-for-data-parallel
Closed

SunMarc wants to merge 1 commit into
mainfrom
disable-kernels-for-data-parallel

Conversation

@SunMarc

@SunMarc SunMarc commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

With kernels on, nn.DataParallel replicas run the layers of the first device: kernelize stores the kernel's forward on each layer, bound to it, and the replicas copy it. Training then silently diverges, or crashes with Expected all tensors to be on the same device when the GPUs can't read each other's memory.

This PR:

  • makes model.use_kernels = False undo kernelize (it was a no-op with a warning): unkernelize removes the forward kernelize stored on each layer, and keeps accelerate's hooks.
  • disables kernels in Trainer, with a warning, before wrapping the model in nn.DataParallel. DDP (torchrun, accelerate launch) is not affected and keeps the kernels.

Reproducer

Trainer on 2 GPUs launched with python (so nn.DataParallel), a tiny Llama loaded with device_map="cuda:0", 20 steps:

model = AutoModelForCausalLM.from_pretrained(path, device_map="cuda:0", use_kernels=True)
trainer = Trainer(model=model, args=TrainingArguments(..., max_steps=20, eval_strategy="steps", eval_steps=10), ...)
trainer.train()
train losses eval losses
use_kernels=False [6.95716, 6.88717] [6.81036, 6.75083]
use_kernels=True, main [6.96008, 6.93827] [6.89926, 6.88458]
use_kernels=True, this PR [6.95716, 6.88717] [6.81036, 6.75083]

Tests

  • test_unkernelize now checks that disabling kernels removes them, instead of the old no-op warning.
  • test_unkernelize_restores_class_forward: CPU test with a patched kernelize.

`kernelize` stores the kernel's forward on each layer, bound to it, and
`nn.DataParallel` replicas copy it: every replica then runs the layers of
the first device. Training silently diverges, or crashes when the GPUs can't
read each other's memory.

`model.use_kernels = False` now undoes `kernelize` (it was a no-op), and
`Trainer` disables kernels before wrapping the model in `nn.DataParallel`.
@SunMarc SunMarc closed this Nov 25, 2026
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants