r/pytorch • u/SkyGold8322 • 20d ago
Accessing a model's individual layer
I want to access one of a LLM's individual layers and get output from it (like how nn.Linear() works). I tried using model.layer[0](tokenizer.encode("hi")) but that wouldn't work. If someone can give me the proper way to do this, it would be appreciated. I'm using Python for this with the transformers and pytorch library
3
Upvotes
3
u/HeeebsInc 19d ago
When initializing the model create a hook in the layer you want then pass input normally. If the hook is made properly you can inject logic to dump outputs of this layer and pass output to the rest of the model. Hooks are useful for custom training or general debugging. Note if you do anything like print in the hook it will be slow. Also avoid torch compile with debugging hooks.
Drop everything I said into ChatGPT or Claude and it will give you code to do exactly what I described on the layer index you want.
Good luck
1
u/graphbook 15d ago
Torchlens might make it easier as well https://github.com/johnmarktaylor91/torchlens